Allow Cors Origin in ASP.NET Core
Solution 1
Amy's right in her comment. CORS headers need to be set by the target server, not yours.
You will often find issues with CORS if you are trying to hook into an API on a different port but running locally on the same IP address (a most common example is localhost:<> trying to ping localhost<>, etc.).
If you are trying to run this on your local machine with Google chrome you can download the below extension which will allow you to toggle on and off the CORS rule so you can test locally: Allow CORS: Access-Control-Allow-Origin
Solution 2
I've just lost a couple of minutes trying to figure out why CORS isn't working for requests from http://localhost:8080 that I've setup according to the official documentation.
Well it's because I added a '/' at the end of the URL. So, remove your '/' from the allowed origins.
There's even a Note on the Microsoft docs about this!
Note: The URL must not contain a trailing slash (/). If the URL terminates with /, the comparison returns false and no header is returned.
Solution 3
This is the exmple provided here:ASP.NET Core 2.2
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
options.AddPolicy("AllowSpecificOrigin",
builder => builder.WithOrigins("http://example.com"));
});
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env,
ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
// Shows UseCors with named policy.
app.UseCors("AllowSpecificOrigin");
app.Run(async (context) =>
{
await context.Response.WriteAsync("Hello World!");
});
}
The finally use it like this on the controller or action:
[EnableCors("AllowSpecificOrigin")]
Also for some reason make sure that app.UseCors is called before app.UseMVC.
Also if all you need is CORS from a single origin; you use simpler solution with no policies:
public void ConfigureServices(IServiceCollection services)
{
services.AddCors();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
app.UseCors(
options => options.WithOrigins("http://example.com").AllowAnyMethod()
);
app.UseMvc();
}
Solution 4
I know this is an old question but if like me you're using the appsettings.json
file for configuration, be sure to add this:
"cors": {
"rules": [
{
"origin": "https://localhost:44379",
"allow": true
}
]
}
This simple addition made everything magically work for me.
Solution 5
Simple and easy way to do it.
- Install package
Install-Package Microsoft.AspNetCore.Cors
- Put the code below in startup.cs file
app.UseCors(options => options.AllowAnyOrigin());
Christian Herrejon
Updated on July 07, 2022Comments
-
Christian Herrejon almost 2 years
I am using Microsoft.ApsNetCore.Cors 2.2
"Access to XMLHttpRequest at 'exampleapi.local' from origin 'example.local' has been blocked by CORS policy:
No 'Access-Control-Allow-Origin' header is present on the requested resource."I set the settings with this:
public void ConfigureServices(IServiceCollection services) { services.AddCors(options => { options.AddPolicy("AllowSpecificOrigin", builder => { builder .AllowAnyOrigin() .AllowAnyMethod() .AllowAnyHeader(); }); }); services.Configure<TokenSettings>(this.Configuration.GetSection("Tokens")); services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(opt => { opt.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true, ValidateAudience = true, ValidateLifetime = true, ValidateIssuerSigningKey = true, ValidIssuer = Configuration["Tokens:Issuer"], ValidAudience = Configuration["Tokens:Audience"], IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(Configuration["Tokens:SecurityKey"])) }; }); services.AddMvc(); services.Configure<LdapConfig>(Configuration.GetSection("ldap")); services.AddScoped<ILdapAuthenticationService, LdapAuthenticationService>(); services.AddScoped<IUserService, UserService>(); services.AddScoped<IProjectService, ProjectService>(); services.AddScoped<IProjectMembersService, ProjectMembersService>(); services.AddScoped<IJourneyUsersService, JourneyUsersService>(); services.AddScoped<IProjectRolesService, ProjectRolesService>(); services.AddScoped<IPmoGuardianService, PmoGuardianService>(); services.AddScoped<IHolidaysService, HolidaysService>(); services.AddScoped<IMailService, MailService>(); services.AddScoped<INotificationsService, NotificationsService>(); services.AddScoped<INotificationUsersService, NotificationUsersService>(); services.Configure<AWSConfigSes>(Configuration.GetSection("AWSSmtp")); services.AddDbContext<JourneyContext>(options => options.UseSqlServer(Configuration.GetConnectionString("JourneyConnection"))); services.AddDbContext<TSMContext>(options => options.UseSqlServer(Configuration.GetConnectionString("TSMConnection"))); services.AddDbContext<PmoGuardianContext>(options => options.UseSqlServer(Configuration.GetConnectionString("PmoGuardianConnection"))); } public void Configure(IApplicationBuilder app, IHostingEnvironment env, IMailService mail, INotificationsService not) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } Recurrence recurrency = Recurrence.GetInstance(not); //new TSMClockService(mail); app.UseCors("AllowSpecificOrigin"); app.UseAuthentication(); app.UseMvc(); } [Produces("application/json")] [Route("api/Mail")] [EnableCors("AllowSpecificOrigin")]
But It doesn't work, always I got the same error
-
Christian Herrejon over 5 yearsI tried both but It doesn't work, anyway I am grateful
-
Christian Herrejon over 5 yearsThank you. If I am on localhost, the API works fine but if I am on production, the API gets the error