简体   繁体   中英

Send binarydata to Azure webAPI POST endpoint

Currently my webAPI has the following POST endpoint:

public async Task<ActionResult<string>> AddUserImage([FromRoute] string userId, [FromHeader] bool doNotOverwrite, [FromBody] byte[] content, CancellationToken ct)

My goal is to send an image file to the endpoint. However, I cannot find a correct way to send an octect-stream or ByteArrayContent or some other type over the internet. All attempts end in an HTTP 415.

This is my best attempt to send the image over the internet:

public async Task<bool> AddOrReplaceImage(string id, string endpoint, byte[] imgBinary)
{
    if (imgBinary is null) throw new ArgumentNullException(nameof(imgBinary));

    var request = new HttpRequestMessage(HttpMethod.Post, endpoint);
    request.Headers.Add("doNotOverwrite", "false");
    request.Content = JsonContent.Create(imgBinary);
    // I also tried: request.Content = new ByteArrayContent(imgBinary);
    request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); // Does not seem to change a thing
            
    var apiResult = await new HttpClient().SendAsync(request); // Returns 415
    return apiResult.IsSuccessStatusCode;
}

I doubt both the parameters of the endpoint and the way I send the HTTP request. How can I simply receive and send an image over the internet?

You can try [FromForm] and IFormFile Like this:-

public class PhotoDetails
{
  public string id {get;set;}
  public string endpoint {get;set;}
  public IFormFile photo {get;set;}
}

public async Task<ActionResult<string>> AddUserImage([FromForm] PhotoDetails photoDetails, CancellationToken ct)

I tried this in .net core and it worked but i needed array of files so i used [FromForm] and IFormFile[].

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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