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
相关产品推荐
相关产品推荐

