I am trying to call the WebAPI method to get some data, but it throws a Cross-Origin Read Blocking (CORB) blocked cross-origin response https://localhost:44332/api/Controller/Action with MIME type text/html. even though I have enabled CORS in my ConfigureServices Method and used the policy in the Configure method in the startup
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
options.AddPolicy("AllowAll",
builder =>
{
builder
.WithOrigins("http://localhost:4200/")
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials();
});
});
services.AddMvc();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
.....
app.UseCors("AllowAll");
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
What could the reason be?
So, Basically as CRice and johnny commented, Internal server error are propagated as CORS Error.
Since it is good practice to handle all errors within the application, doing so will make sure 500 Internal Server Error will be intact even in the case of an exception and not be masked as CORS Error.
It can be understood better here
This might help,
Note: The URL must not contain a trailing slash (/). If the URL terminates with /, the comparison returns false and no header is returned.
Related
I am currently following this basic signal R tutorial.
But because I want to use it in an existing project I split it up. The Hub is inside a different project than the client. Therefore the IP address is different. Inside the configuration of the Hub I of course enabled cors:
public void ConfigureServices(IServiceCollection services)
{
services.AddCors();
services.AddControllers();
services.AddSignalR();
//other configuration code
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env){
app.UseRouting();
app.UseCors(x => x
.AllowAnyMethod()
.AllowAnyHeader()
.AllowAnyOrigin()
);
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
endpoints.MapHub<LiveUpdating.ChatHub>("/chatHub");
});
}
However when I now try to connect to the chatHub in my client (setup is exactly the same as in the link above except that I changed the connection to var connection = new signalR.HubConnectionBuilder().withUrl("https://localhost:44316/chatHub").build(); ) I get this error:
Access to fetch at 'https://localhost:44316/chatHub/negotiate?negotiateVersion=1' from
origin 'https://localhost:44341' has been blocked by CORS policy: Response to preflight
request doesn't pass access control check: The value of the 'Access-Control-Allow-Origin'
header in the response must not be the wildcard '*' when the request's credentials mode
is 'include'.
Shouldn't this normally work, when I add the app.UseCors as seen above. Because for all my other Rest Controllers it works fine.
Replacing the app.useCors with
app.UseCors(x => x
.AllowAnyMethod()
.AllowAnyHeader()
.SetIsOriginAllowed(origin => true)
.AllowCredentials());
fixes the bug
I have a .NET core web api. It works as expected when requesting from Postman but returning
Status Code: 500 Internal Server Error
Referrer Policy: strict-origin-when-cross-origin
when requested from other React JS client. I have already enabled CORS in the Startup.cs like this:
public void ConfigureServices(IServiceCollection services)
{
services.AddCors();
services.AddMvc();
...
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory)
{
app.UseCors(x => x.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());
...
}
But still getting the Status Code: 500 Internal Server Error. I have been trying to solve this issue for too long. Please help. Thanks.
add this in your configure method:
// global cors policy
app.UseCors(x => x
.SetIsOriginAllowed(origin => true)
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials());
if its not solved then add a custom middleware and check your request you can use ilogger for logging exception.
follow this link for middleware: https://www.tutorialsteacher.com/core/how-to-add-custom-middleware-aspnet-core
I have a global CORS policy which is applicable for all the endpoints but I want to override this policy for the signalR hub end point.
Here is my ConfigureServices method which has a global CORS policy which I cant modify
public void ConfigureServices(IServiceCollection services)
{
// some piece of code before adding CORS
services.AddCors(o =>
{
o.AddDefaultPolicy(p =>
{
p.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod();
});
});
// some piece of code after adding CORS
}
Here is the Configure method
public void Configure(IApplicationBuilder app, IServiceProvider serviceProvider)
{
app.UseCors();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endPoints =>
{
endPoints.MapControllers();
endPoints.MapHub<NotificationHub>("/notificationHub")
.RequireCors((builder) =>
{
builder
.WithOrigins(_configuration.GetValue<string>("Settings:ClientAppUrl"))
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials();
});
});
}
As it is clear that I have overwritten the CORS policy for the particular endpoint of signal which is /notificationHub.
I am getting the same CORS error in the browser as I was getting before adding the CORS policy for the /notificationHub/negotiate
Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow->Credentials' header in the response is '' which must be 'true' when the request's credentials mode is >'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the >withCredentials attribute.
Also please note that if I add AllowCredentials() method in the global CORS policy then signalR works properly but my objective here is to add the new CORS policy only for the signalR endpoint.
I am not using OWIN CORS, it is just Microsoft.AspNetCore.Cors.
I have found the fix for this. It is simple but often ignored.
The order of middleware matters here a lot. By swapping the below two middleware, I got it working.
OLD
app.UseCors();
app.UseRouting();
NEW
app.UseRouting();
app.UseCors();
If anyone facing this issue, try doing this. It would definitely work.
This doc from Microsoft supports this claim.
I found interesting problem. I deployed my ASP.NET Core REST API on IIS and when I called it, I had this error:
Access to XMLHttpRequest at 'https...' from origin 'https:...' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The 'Access-Control-Allow-Origin' header contains multiple values '*, *', but only one is allowed.
Uncaught DOMException: Failed to execute 'send' on 'XMLHttpRequest': Failed to load 'https:'.
but it was working few minutes ago. I checked the response header and this was there:
access-control-allow-headers: content-type,odata-maxversion,odata-version
access-control-allow-methods: GET, GET,POST,PUT,DELETE,OPTIONS
access-control-allow-origin: *, *
Then I realised I restarted the service. For some reason my code and IIS duplicate HTTP response header values every time the service is uploaded. When I delete HTTP Response Header values in IIS, it works. This is my Startup.cs code:
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(o => o.AddPolicy("AllPolicy", builder =>
{
builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader();
}));
services.AddControllers();
...
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseCors("AllPolicy");
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
Do you have any ideas why are the header values duplicated everytime when is the service uploaded? And do you have any ideas how to fix it?
Try moving the "app.UseCors("AllPolicy");" to right after app.UseRouting();
so that it looks like:
app.UseRouting();
app.UseCors("AllPolicy");
Actually this is not a duplication post,I know a part of the title asked many times in stackoverflow community, I read all posts, and answers, but I think my problem and technologies which I used are different.
First of all I should mention ASP.NET Core WEB/API is my back-end-app and Reactjs is my front Application.
I read about CORS and I found out I must enable CORS on ASP.NET App and put 'Access-Control-Allow-Origin':'*' on my request's header, but I still have the below error while I call an api:
No 'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'http://localhost:8080' is therefore not allowed
access. The response had HTTP status code 500. If an opaque response
serves your needs, set the request's mode to 'no-cors' to fetch the
resource with CORS disabled.
This is my Startup.cs code related to CORS:
public void ConfigureServices(IServiceCollection services)
{
// other lines of code
services.AddCors(options =>
{
options.AddPolicy("AllowAll",
builder =>
{
builder
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader();
});
});
services.Configure<MvcOptions>(options =>
{
options.Filters.Add(new CorsAuthorizationFilterFactory("AllowAll"));
});
// other lines of code
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
app.UseCors("AllowAll");
app.UseAuthentication();
app.UseMvc();
}
This is my react code:
function save(message) {
const requestOptions = {
method: 'POST',
mode: 'cors',
headers: { ...authHeader(),
'Content-Type': 'application/json',
'Access-Control-Allow-Origin':'*',
},
body: JSON.stringify(message)
};
return fetch(config.apiUrl + '/message/save', requestOptions).then(handleResponse, handleError);
}
Thanks for your responding.
I had a similar problem recently. In my case it started working when I added services.AddCors(); in my ConfigureServices method and this part of code
app.UseCors(builder => builder
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials());
in my Configure method. Remember to add those BEFORE UseMvc() call in both cases.
After two difficult days finally I found out how can I fix my problem. Actually one of your comment was a nice clue for me.
#kirk-larkin said:
The response had HTTP status code 500 is key here. When there's an exception in your ASP.NET Core project, the CORS headers are cleared. You should try and find out why an exception is being thrown.
I traced my code many times, then i found out I forget to register a service which I used in my controller in Startup.cs.
I called these below code in Startup.cs and my problem solved.
services.AddScoped<IMessageService, MessageService>();
With ASP.NET Core 2.1, when the controller throws an exception, which results in an error 500, the CORS headers are not sent. This should be fixed in the next version but until then you could use a middleware to fix this.
see
https://github.com/aspnet/CORS/issues/90#issuecomment-348323102
https://github.com/aspnet/AspNetCore/issues/2378
https://github.com/aspnet/CORS/issues/46
Also note that with credentials you need to explicitly add WithOrigins with host and port since most browsers simply ignore it otherwise (see https://stackoverflow.com/a/19744754/2477619):
app.UseCors(builder =>
builder
.WithOrigins("http://localhost:4200")
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials()
);
As said by #Siavash the fact that it is returning 500 may indicate there is an issue with the build. I was having this problem today as it was working fine on localhost but was failing when deployed.
To debug the error, find this line in your web.config file in the root of the IIS directory:
<aspNetCore processPath="dotnet" arguments=".\CarpetrightBackend.dll" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" hostingModel="inprocess" />
Change stdoutLogEnabled="false" to true and then you will be able to see the error in the log file generated.
In my case I forgot to incude some static csv files when deploying that the program needed to reference and return data from it.