【问题标题】:Sending file to API with Authorization .Net 5使用授权.Net 5将文件发送到API
【发布时间】:2021-05-04 13:28:13
【问题描述】:

在我的系统上,我需要将从表单接收到的文件发送到将保存在 Azure 中的 API。 对于此发送,我需要传递一个承载令牌,这是我能够制作和接收的令牌部分,由邮递员测试,我可以发送和接收生成文件的访问 url。 在我的 .Net 项目中,我无法发送文件并接收其 url 以写入数据库。我需要传递此令牌并将上传到 API URL。 我会把目前写的代码放上来。

[HttpPost]
public async Task<IActionResult> UploadAzure([FromForm] IFormFile file)
{
    var Token = await _tokenAzure.ReturnToken();
    var _urlApi = "https://mysite.dev/api/file/savepdf";
    var _tokenApi = Token.AccessToken;

    if (file == null || file.Length == 0)
        return Content("file not selected");

    HttpClientHandler clientHandler = new HttpClientHandler();
    clientHandler.ServerCertificateCustomValidationCallback = (sender, cert, chain, sslPolicyErrors) => { return true; };

    // Pass the handler to httpclient(from you are calling api)
    HttpClient client = new HttpClient(clientHandler);

    byte[] data;
    using (var br = new BinaryReader(file.OpenReadStream()))
        data = br.ReadBytes((int)file.OpenReadStream().Length);
    ByteArrayContent bytes = new(data);
    MultipartFormDataContent multiContent = new()
    {
        { bytes, "file", file.FileName }
    };

    var result = client.PostAsync(_urlApi, multiContent).Result;



    return RedirectToAction("Index");
}

【问题讨论】:

    标签: c# .net azure api


    【解决方案1】:

    您可能想要添加以下代码行。

    client.DefaultRequestHeaders.Authorization =new AuthenticationHeaderValue("Bearer", _tokenApi);
    

    【讨论】:

      猜你喜欢
      • 2021-12-04
      • 2015-07-24
      • 1970-01-01
      • 2021-04-06
      • 1970-01-01
      • 1970-01-01
      • 2016-06-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多