发送一个表单POST HTTP请求(Content-Type: application/x-www-form-urlencoded)到下面的控制器,结果是一个HTTP 415不支持的媒体类型响应。

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

表单post HTTP报头:

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

这在过去是与ASP一起工作的。NET MVC 5在。NET 4.6。


当前回答

“HTTP 415不支持的媒体类型响应”源于请求头中的内容类型。例如在javascript中通过axios:

Axios({
            method: 'post',
            headers: { 'Content-Type': 'application/json'},
            url: '/',
            data: data,  // an object u want to send
          }).then(function (response) {
            console.log(response);
          });

其他回答

这个问题可能是因为MVC的MW。你必须在MVC选项中设置formatterType:

services.AddMvc(options =>
            {
                options.UseCustomStringModelBinder();
                options.AllowEmptyInputInBodyModelBinding = true;
                foreach (var formatter in options.InputFormatters)
                {
                    if (formatter.GetType() == typeof(SystemTextJsonInputFormatter))
                        ((SystemTextJsonInputFormatter)formatter).SupportedMediaTypes.Add(
                            Microsoft.Net.Http.Headers.MediaTypeHeaderValue.Parse("text/plain"));
                }
            }).AddJsonOptions(options =>
            {
                options.JsonSerializerOptions.PropertyNameCaseInsensitive = true;
            });

“HTTP 415不支持的媒体类型响应”源于请求头中的内容类型。例如在javascript中通过axios:

Axios({
            method: 'post',
            headers: { 'Content-Type': 'application/json'},
            url: '/',
            data: data,  // an object u want to send
          }).then(function (response) {
            console.log(response);
          });

请遵循以下步骤:

添加到发送请求头内容类型字段: axios。邮报》(' /订单/ ',orderId、 { headers: {'Content-Type': 'application/json'} }) 使用axios发送的每个数据(简单或复杂类型)都不应该放置任何额外的括号(axios。post('/Order/', orderId,…))。

警告!字符串类型有一个例外——在发送前对其进行stringify (axios。post('/Order/', JSON.stringify(address),…))。

添加方法到控制器: (HttpPost) ([FromBody]int orderId) { 还好(); }

我复制了一个POST请求,并在邮递员中更改为GET,然后得到415错误。

修复方法是删除Body中的键-值对,因为这是一个GET请求。

在我的情况下,我收到了HTTP 415不支持的媒体类型响应,因为我指定的内容类型为文本而不是JSON,所以简单地改变类型解决了这个问题。 请在下面的博客文章中查看更详细的解决方案: https://www.howtodevelop.net/article/20/unsupported-media-type-415-in-aspnet-core-web-api