When I do axios post by React JS, I get the following CORS error to ASP.Net Core side.
Failed to load resource: Origin http://localhost:3000 is not allowed
by Access-Control-Allow-Origin.
https://localhost:5001/api/vendorregistration
I installed the following as my Nuget Packages and did not apply any other form below but it didn’t work.
- Microsoft.AspNet.Cors. 5.2.7 Version
- Microsoft.AspNetCore.Cors 2.1.1 Version
How to enable Cors for every type of request in asp.net core 3.1
Startup.cs
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddCors(o => o.AddPolicy("ReactPolicy", builder =>
{
builder.AllowAnyHeader()
.AllowAnyMethod()
.AllowAnyOrigin();
// .AllowCredentials();
}));
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseHttpsRedirection();
app.UseCors("ReactPolicy");
app.UseMvc();
}
}
VendorRegistrationController.cs
namespace Bait.Controllers
{
[Produces("application/json")]
[Route("api/[controller]")]
[ApiController]
[EnableCors("ReactPolicy")]
ReactJS Side RegistrationForm.tsx
const handleFormSubmit = async (values: any): Promise<any> => {
const response = await axios.post<User>('https://localhost:5001/api/vendorregistration', { data: values })
console.log(response);
};
2
Answers
you do not have to use in every actions in the controller. just put app.UseCors("ReactPolicy"); line before
app.UseStaticFiles(); line
Hope it’ll work!
Could you pls check my code snippet as it worked for me. I copied your startup file so I just put the using packages here.
My test controller:
And my startup file:
And my test react code: