How should I format an Angular POST to a WebAPI endpoint?

40 Views Asked by At

I am trying to send an image from an Angular app to the endpoint. However, I get the following exception from the backend : Http failure response for http://localhost:[port]/api/sendimage: 415 Unsupported Media Type

My Angular code is the following :

  const data = receivedImage;
  const headers = new HttpHeaders({
    'Content-Type': 'application/json' // Set the content type to JSON
  });

  this.http.post<any>('http://localhost:[port]/api/sendimage', data, { headers })
  .subscribe(
    response => {
      console.log('Response from server:', response);
      // Handle response as needed
    },
    error => {
      console.error('Error:', error);
      // Handle error
    }
  );

And my endpoint looks like this:

[HttpPost]
[Route("api/sendimage")]
public async Task<HttpResponseMessage> UploadImage()
{
    // Check if the request contains multipart/form-data.
    if (!Request.Content.IsMimeMultipartContent())
    {
        throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
    }
...process the image

What am I doing wrong?

0

There are 0 best solutions below