简体   繁体   English

使用 Authorization.Net 5 将文件发送到 API

[英]Sending file to API with Authorization .Net 5

On my system I need to send a file received from a form to an API that will be saved in Azure.在我的系统上,我需要将从表单接收到的文件发送到 API,该文件将保存在 Azure 中。 For this sending I need to pass a Bearer Token, the part of the token I was able to make and receive, testing by Postman I can send and receive the access url of the generated file.对于此发送,我需要传递一个承载令牌,这是我能够制作和接收的令牌部分,通过 Postman 测试我可以发送和接收生成文件的访问 url。 In my.Net project I am not able to send the file and receive its url to write to the database.在 my.Net 项目中,我无法发送文件并接收其 url 以写入数据库。 I need to pass this Token and make the uplad to the API URL.我需要传递这个令牌并将上传到 API URL。 I'll put the code I wrote so far.我会放上我到目前为止写的代码。

[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");
}

You maybe want to add the following line of code.您可能想要添加以下代码行。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM