Send binarydata to Azure webAPI POST endpoint

Viewed 33

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?

1 Answers

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

If controller is annotated with [ApiController] then[FromXxx] is required. For normal view controllers it can be left.

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[].

Related