[英]web api 2 CORS No 'Access-Control-Allow-Origin' header is present
[英]Unable to add Access-Control-Allow-Origin header on API response
我目前正在将一个项目从 .Net Framework 转换为 .Net 5。
当我点击新的 .Net 5 项目中的端点之一时,出现以下异常。
System.InvalidOperationException: '误用的标头名称,'Access-Control-Allow-Origin'。 确保请求标头与 HttpRequestMessage 一起使用,响应标头与 HttpResponseMessage 一起使用,内容标头与 HttpContent 对象一起使用。
端点看起来像这样,在我将“Access-Control-Allow-Origin”添加到响应内容标头的行上抛出异常。
[HttpGet]
[Route("api/Recommendations/GetRecommendations/{id}/{count}")]
public HttpResponseMessage GetRecommendations(int id, int count)
{
var response = new HttpResponseMessage();
response.Content = new StringContent(_recommendationsAPIService.GetRecommendations(id, count));
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
response.Content.Headers.Add("Access-Control-Allow-Origin", "*");
response.Content.Headers.Add("Access-Control-Allow-Headers", "Content-Type, Accept, Referer, Authorization,Sec-Fetch-Mode,User-Agent");
return response;
}
如何修复此异常?
我不熟悉最初编写该项目的人,所以是否有任何理由将这些标题添加到响应中?
两件事情:
1st - 您在内容上添加标题。 该消息很清楚,您应该将其添加到响应中。 在此处查看: 在 ApiController 中添加自定义响应标头以了解将其添加到响应的方式
response.Headers.Add("X-Students-Total-Count", students.Count());
第二 - CORs 是您需要在全球范围内应用的东西! 在此处查看如何配置您的 api 以执行此操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.