ASP.NET Core 表单 POST 导致 HTTP 415 Unsupported Media Type 响应 [英] ASP.NET Core form POST results in a HTTP 415 Unsupported Media Type response

查看:61
本文介绍了ASP.NET Core 表单 POST 导致 HTTP 415 Unsupported Media Type 响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

向以下控制器发送表单 POST HTTP 请求 (Content-Type: application/x-www-form-urlencoded) 会导致 HTTP 415 Unsupported Media Type回应.

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)
    {
        //...
    }
}

表单发布 HTTP 标头:

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

这曾经适用于 .NET 4.6 上的 ASP.NET MVC 5.

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

推荐答案

对于表单,使用 [FromForm] 属性而不是 [FromBody] 属性.

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

以下控制器适用于 ASP.NET Core 1.1:

The below controller works with ASP.NET Core 1.1:

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

注意:如果您的控制器使用[ApiController] 进行注释,则需要[FromXxx].对于普通的视图控制器,可以省略.

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

这篇关于ASP.NET Core 表单 POST 导致 HTTP 415 Unsupported Media Type 响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆