发送一个表单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。


当前回答

你必须指定编码和内容类型,例如:

        var request = new HttpRequestMessage
        {
            Method = new HttpMethod("POST"),
            RequestUri = new Uri(CombineUrl(_baseUrl, _resource))
        };
        request.Content = new StringContent(contentBody, System.Text.Encoding.UTF8, "application/json");

其他回答

这个问题可能是因为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;
            });

在我的情况下,我有一个方法在我的控制器需要一个输入参数;不幸的是,调用者(HttpClient)没有传递它。 真可耻。

请遵循以下步骤:

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

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

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

另一个值得注意的陷阱是确保你没有使用下面的消费属性来装饰控制器:

[Produces("application/json")]
[Consumes("application/json")]
public class MyController : Controller

如果上载不是JSON,这将失败与415不支持的媒体类型。

“我的一个朋友”最近被这样的事情所揭穿:

public class MyFileUploadController : MyCustomController {

}

[Produces("application/json")]
[Consumes("application/json")]
public class MyCustomController : ControllerBase {

}

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