Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET Core form POST results in a HTTP 415 Unsupported Media Type response

Sending a form POST HTTP request (Content-Type: application/x-www-form-urlencoded) to the below controller results into a HTTP 415 Unsupported Media Type response.

public class MyController : Controller {     [HttpPost]     public async Task<IActionResult> Submit([FromBody] MyModel model)     {         //...     } } 

Form post HTTP headers:

POST /submit HTTP/1.1 Host: example.com:1337 Connection: keep-alive Content-Length: 219 Pragma: no-cache Cache-Control: no-cache Origin: https://example.com:1337 Upgrade-Insecure-Requests: 1 User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36 Content-Type: application/x-www-form-urlencoded Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8 Referer: https://example.com:1337/submit Accept-Encoding: gzip, deflate, br Accept-Language: en-US,en;q=0.8,nl;q=0.6 

This used to work with ASP.NET MVC 5 on .NET 4.6.

like image 280
Bart Verkoeijen Avatar asked Jun 14 '17 07:06

Bart Verkoeijen


People also ask

How do I fix HTTP 415 unsupported media type?

Fixing 415 Unsupported Media Type errorsEnsure that you are sending the proper Content-Type header value. Verify that your server is able to process the value defined in the Content-Type header. Check the Accept header to verify what the server is actually willing to process.

What is difference between FromForm and FromBody?

[FromForm] - Gets values from posted form fields. [FromBody] - Gets values from the request body.

What does HTTP Error 415 mean?

The HTTP 415 Unsupported Media Type client error response code indicates that the server refuses to accept the request because the payload format is in an unsupported format. The format problem might be due to the request's indicated Content-Type or Content-Encoding , or as a result of inspecting the data directly.

What is FromBody?

Using [FromBody] When a parameter has [FromBody], Web API uses the Content-Type header to select a formatter. In this example, the content type is "application/json" and the request body is a raw JSON string (not a JSON object). At most one parameter is allowed to read from the message body.


1 Answers

For forms, use the [FromForm] attribute instead of the [FromBody] attribute.

The below controller works with ASP.NET Core 1.1:

public class MyController : Controller {     [HttpPost]     public async Task<IActionResult> Submit([FromForm] MyModel model)     {         //...     } } 

Note: [FromXxx] is required if your controller is annotated with [ApiController]. For normal view controllers it can be omitted.

like image 112
Bart Verkoeijen Avatar answered Sep 22 '22 10:09

Bart Verkoeijen