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

ASP.NET Core 5 POST请求报CORS错误,Content-Type头不被允许如何解决?

问题排查与解决方案

第一步:修复CORS配置错误

你当前CORS配置里允许的源是https://localhost:47717,但报错中的请求源是http://localhost:47717,协议不一致导致CORS规则不匹配。直接修改Startup.cs里的CORS配置:

services.AddCors(options =>
{
    options.AddPolicy(allowSpecificOrigins,
    builder =>
    {
        // 注意协议、域名、端口三者必须和请求源完全匹配
        builder.WithOrigins("http://localhost:47717")
                .AllowAnyHeader()
                .AllowAnyMethod();
    });
});

同时要确保Configure方法里的中间件顺序正确,必须先启用CORS中间件,再加路由、授权中间件:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    // 其他前置配置
    app.UseCors(allowSpecificOrigins);
    app.UseRouting();
    app.UseAuthorization();
    // 其他后续配置
}

第二步:修复参数绑定问题

CORS问题解决后如果还是收不到提交对象,做以下检查:

  • 确认CustomerDetail类的属性和前端提交的JSON字段完全匹配,属性必须是公共可写的:
public class CustomerDetail
{
    public string CustomerID { get; set; }
    public string CustomerName { get; set; }
    public string Address { get; set; }
    public string StateId { get; set; }
    public string CityId { get; set; }
    public string LandMark { get; set; }
    public string Mobile { get; set; }
}
  • 前端代码手动序列化提交对象,避免AngularJS默认序列化异常:
this.insertdetails = function (Customer) {
    alert('insertdetails');
    var request = $http({
        method: "POST",
        url: baseUrl + "/api/ApiDisplay/InsertDetails",           
        dataType: "json",
        data: JSON.stringify(Customer),
        contentType:"application/json;charset=utf-8",
    });
    return request;
}
  • 确认控制器添加了[ApiController]特性,该特性会自动启用JSON参数绑定功能。
  • 可以在控制器方法内加断点,查看Request.Body的原始内容,确认请求数据是否正常传入后端。

内容的提问来源于stack exchange,提问作者Abdul mubeen

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 05:15:03