I have developed Asp.Net Core 3.1 API and deployed on the server through IIS, it’s working as expected if I send the GET/POST request from Postman or browser, But Below code is giving error.
$.ajax({
type: 'GET',
crossDomain: true,
dataType: 'json',
url: 'myUrl',
success: function(jsondata){
}
})
Error:
Access to XMLHttpRequest at
‘http://server:8080/API/GetMethod?currency=INR’
from origin ‘http://localhost:63765’ has been blocked by CORS policy:
No ‘Access-Control-Allow-Origin’ header is present on the requested
resource.
I have disabled the CORS from my application using the below code
C# code:
[DisableCors]
[Route("[controller]")]
[ApiController]
[AllowAnonymous]
public class APIController : ControllerBase
{
startup.cs
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddLog4Net();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseCors();
app.UseAuthorization();
So I have tried disabling the CORS on controller level, I have tried jsonp
also instead of JSON
, It’s still getting the same error.
I have two questions here.
- Is this clientside or serverside issue?
- How to fix the error?
Note: I able to send GET requests from browser and Postman, but with this clientside code, I am getting the CORS related issue.
2
Answers
So the issue was due to I was using
[EnableCors("MyPolicy")]
on the controller, but added[DisableCors]
on the method. so it might be overwriting the CORS policy. So I removed[DisableCors]
from the method and it started working as expected.1. It should be server side problem. Because server is blocking the origin who makes request.
2. I had similar problem before in feature. Instead of using
[DisableCors]
and[AllowAnonymous]
, you can make some configuration in startup.csdetails: https://learn.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-3.1
AllowAnyOrigin
: Allows CORS requests from all origins with any scheme (http or https). AllowAnyOrigin is insecure because any website can make cross-origin requests to the app.recomended solution (if this not work you can maybe use AllowAnyOrigin):