ASP.NET Core中GET请求的CORS跨域问题排查
GET请求触发CORS错误的排查与解决
问题场景
后端采用ASP.Net Core Web API,前端用React结合axios调用接口,POST请求响应正常,但调用GET接口时出现CORS错误。
前端代码
export const overviewGet = (orderId: string): Promise<IOrder> => { const URL = `http://{myhost}/orders/overview&id=${orderId}` return axios .get(URL) .then((d: AxiosResponse<IOrder>) => d.data) } export const overviewPost = (orderId: string): Promise<IOrder> => { const URL = `http://{myhost}/orders/overview&id=${orderId}` return axios .post(URL) .then((d: AxiosResponse<IOrder>) => d.data) }
后端CORS配置(Program.cs)
builder.Services.AddCors(options => { options.AddDefaultPolicy(policyBuilder => { policyBuilder .WithOrigins("http://localhost:3000") .AllowAnyHeader() .AllowAnyMethod() ; }); });
控制器代码
[Route("[controller]")] public class OrdersController: ControllerBase { [HttpGet("overview")] public IActionResult Overview(Guid id) => Ok(); [HttpPost("overview")] public IActionResult Overview1(Guid id) => Ok(); }
错误提示
Access to XMLHttpRequest at 'http://{myhost}/orders/overview?id=08da602c-5b76-4f3b-822d-e2c45f05c8ae' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
问题原因及解决办法
前端GET请求URL格式错误
你在overviewGet里的URL参数分隔符用错了:&id=${orderId}应该改成?id=${orderId}。HTTP规范里,URL路径和查询参数的分隔符是?,&是用来分隔多个查询参数的。
错误的URL会导致后端找不到对应的[HttpGet("overview")]路由,返回404状态码。而ASP.NET Core只有在请求匹配到正确的控制器动作时,才会自动添加CORS响应头,404响应不会携带这个头,所以浏览器判定违反CORS策略。
修正后的GET方法代码:export const overviewGet = (orderId: string): Promise<IOrder> => { const URL = `http://{myhost}/orders/overview?id=${orderId}` return axios .get(URL) .then((d: AxiosResponse<IOrder>) => d.data) }额外确认:CORS中间件顺序是否正确
虽然POST请求正常,但还是要检查Program.cs里app.UseCors()的位置是否正确——必须放在app.UseRouting()之后、app.UseAuthorization()之前,否则CORS策略不会生效:app.UseRouting(); app.UseCors(); // 位置不能错 app.UseAuthorization();
内容的提问来源于stack exchange,提问作者Timothy
相关产品推荐
相关产品推荐

