I am currently converting a project from .Net Framework into .Net 5.
When I hit one of the endpoints within the new .Net 5 project I get the following exception.
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.'
The endpoint looks like this, the exception is thrown on the line where I add "Access-Control-Allow-Origin" onto the response content 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;
}
How do I fix this exception?
I am not familiar with who originally wrote the project so is there any reason to add these headers onto the response anyway?
CodePudding user response:
You should not use the Content.Headers
property to add such headers. Check the documentation: here
Represents the collection of Content Headers as defined in RFC 2616.
So it should be used for very specific headers.
Another Two things:
1st - You are adding the Header on the Content. The message is clear that you should add it to the response. Check here: Add a custom response header in ApiController for the way to add it to the response
response.Headers.Add("X-Students-Total-Count", students.Count());
2nd - CORs is something that you need to apply globally! Check here on how to configure your api to do that.
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);