Currently I am having problem about has been blocked by CORS policy: No 'Access-Control-Allow-Origin'.
I've tried to fix it in many ways but it still doesn't seem to work.
Hope someone can show me how to fix it.
My code:
File Startup.cs
public void ConfigureServices(IServiceCollection services)
...
services.AddCors(options =>
{
options.AddPolicy(name: "AllowAnyOrigin",
builder =>
{
builder.WithOrigins("http://localhost:3000")
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader();
});
});
...
}
public void Configure(IApplicationBuilder app){
...
app.UseCors("AllowAnyOrigin");
...
}
Controller
[HttpPost]
[EnableCors("AllowAnyOrigin")]
public async Task<IActionResult> ChangeInviteSponsors([FromForm] ChangeInviteSponsorsModel changeInviteSponsorsModel)
{
string userId = User.GetUserId();
return Ok(await _inviteSponsorsService.ChangeInviteSponsors(changeInviteSponsorsModel, userId));
}
Error: Access to XMLHttpRequest at 'https://localhost:5560/api/InviteSponsors/ChangeInviteSponsors' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Help me please. Thank you!
CodePudding user response:
To fix the CORS policy violation
issue, try this.
Also, the order of connecting services in the Configure
method is very important.
First, in the ConfigureServices method, the first method before controller mapping should be
services.AddCors();
Second, to allow CORS, change the Configure
method. Add this code after the UseRouting
and before Middlewares and Controller mappings.
app.UseCors(x => x
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials());
This will allow any requests from any external domains.
CodePudding user response:
services.AddCors(o => o.AddPolicy("MyPolicy", builder =>
{
builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader();
}));
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseCors(x => x
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader());
}