Sending File to API with Authorization . Net 5

Asked

Viewed 40 times

0

On my system, I need to send a received form file to an API that will be saved in Azure. For this submission I need to pass a Bearer Token, the part of the token I was able to do and receive, testing by Postman I can send and receive the url that was generated when uploading the file. In my project . Net, I cannot send the file and receive its url to write to the database. I need to pass this token I generated in another class and upload the file using the API URL. I’ll put in the code I’ve written 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");
}
  • 1

    Missing pass token on request.

  • And how should I pass the Token to API?

  • 1

    The way it does in Postman, like a request header.

1 answer

1


Missing pass token for requisition.

Since the HTTP client is only used within this method, you can do so:

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

Ma is also possible to do directly in the instance of MultipartFormDataContent.

multiContent.Headers.Add(new AuthenticationHeaderValue("Bearer", _token));

Note that the first parameter ("Bearer") It’s just an example, you need to put the same header name in Postman.

See more about making HTTP requests in this post of documentation. It’s usually not a good idea to instantiate a HttpClient each time you use, this post can help you understand the reasons and how to do it the best.

  • With the example you gave I already got the status of success, but I still need to receive the URL to write to the bank, would know with the information I spent explain me so how to get the return of this URL that was generated in Azure?

  • @João Aí would have to open another question, this is not part of the scope of this. Even because you must pass on other information so someone can have help with this new question.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.