You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET Web API如何检查并设置缺失的Content-Type请求头?

解决ASP.NET Web API中客户端未发送Content-Type头的问题

我来帮你搞定这个头疼的问题!当客户端POST请求没带Content-Type头时,Web API会默认推断成application/octet-stream,而这种媒体类型通常不支持表单参数绑定,所以才会抛出你看到的错误。咱们可以通过**自定义消息处理程序(DelegatingHandler)**在请求到达控制器之前拦截并修正Content-Type,具体步骤如下:

步骤1:创建自定义DelegatingHandler

这个处理程序会在请求管道中提前介入,检查并设置Content-Type:

public class ContentTypeHandler : DelegatingHandler
{
    protected override async Task<HttpResponseMessage> SendAsync(
        HttpRequestMessage request, CancellationToken cancellationToken)
    {
        // 仅处理有实体内容的POST请求
        if (request.Method == HttpMethod.Post && request.Content != null)
        {
            var contentType = request.Content.Headers.ContentType;
            
            // 如果Content-Type为空或未设置,强制设为application/x-www-form-urlencoded
            if (contentType == null || string.IsNullOrWhiteSpace(contentType.MediaType))
            {
                request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/x-www-form-urlencoded");
            }
        }

        // 继续传递请求到下一个处理环节
        return await base.SendAsync(request, cancellationToken);
    }
}

步骤2:注册自定义处理程序

把这个处理程序添加到Web API的配置中,让它生效:

对于ASP.NET Web API 2(Global.asax.cs)

在Application_Start方法里的Web API配置部分添加:

protected void Application_Start()
{
    GlobalConfiguration.Configure(WebApiConfig.Register);
    
    // 注册自定义Content-Type处理程序
    GlobalConfiguration.Configuration.MessageHandlers.Add(new ContentTypeHandler());
}

对于ASP.NET Core Web API(Program.cs)

如果是Core版本,需要在服务配置中注册适配的处理逻辑:

builder.Services.AddTransient<ContentTypeHandler>();
builder.Services.AddControllers(options =>
{
    options.Filters.Add<ContentTypeHandler>();
});

步骤3:确保控制器POST方法能正确绑定参数

你的POST方法可以正常接收表单参数,比如:

public IHttpActionResult Post([FromForm] UserModel model)
{
    // 处理业务逻辑
    return Ok("请求处理成功");
}

public class UserModel
{
    public string Username { get; set; }
    public string Password { get; set; }
}

这样一来,即使客户端没发送Content-Type头,咱们的处理程序也会自动把它设置成application/x-www-form-urlencoded,Web API就能正常解析表单参数,不会再抛出那个错误啦!

内容的提问来源于stack exchange,提问作者Satish Yadav

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 10:38:45