无法在 API 响应中添加 Access-Control-Allow-Origin header

Unable to add Access-Control-Allow-Origin header on API response

我目前正在将一个项目从 .Net Framework 转换为 .Net 5。

当我点击新的 .Net 5 项目中的端点之一时,出现以下异常。

System.InvalidOperationException: 'Misused header name, 'Access-Control-Allow-Origin'. Make sure request headers are used with HttpRequestMessage, response headers with HttpResponseMessage, and content headers with HttpContent objects.'

端点看起来像这样,在我将“Access-Control-Allow-Origin”添加到响应内容 header.

的行抛出异常
 [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;
            }

如何修复此异常?

我不熟悉项目的最初编写者,所以是否有任何理由将这些 header 添加到响应中?

你不应该使用 Content.Headers 属性 添加这样的 headers。查看文档:here

Represents the collection of Content Headers as defined in RFC 2616.

所以它应该用于非常具体的headers。

另外两件事:

1st - 您要在内容中添加 Header。该消息很明确,您应该将其添加到响应中。在此处查看:Add a custom response header in ApiController 了解将其添加到响应的方式

 response.Headers.Add("X-Students-Total-Count", students.Count());

2nd - CORs 是您需要在全球范围内应用的东西!检查 here 如何配置你的 api 来做到这一点。

TLDR;

public void ConfigureServices(IServiceCollection services)
    {
        services.AddCors(options =>
        {
            options.AddPolicy(name: MyAllowSpecificOrigins,
                              builder =>
                              {
                                  builder.WithOrigins("http://example.com",
                                                      "http://www.contoso.com");
                              });
        });

        // services.AddResponseCaching();
        services.AddControllers();
    }
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        // Some code here

        app.UseCors(MyAllowSpecificOrigins);