I am trying to establish the connection between Angular and my .net API using Cors. I keep getting this error :
localhost/:1 Access to XMLHttpRequest at 'https://localhost:44378/api/OffRec' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
In order to fix this error. I added the addCors in my ConfigureServices and userCors in Configure like so:
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
options.AddPolicy("CorsPolicy",
builder =>
{
builder.WithOrigins(new string[] { "http://localhost:4200" , "https://localhost:44378/api/offrec" }).AllowAnyMethod().WithHeaders("Access-Control-Allow-Origin");
});
});
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
services.AddControllers();
services.AddDbContext<db_recloadContext>();
}
My Configure method just useCors:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseHsts();
}
app.UseRouting();
app.UseCors("CorsPolicy");
app.UseHttpsRedirection();
// app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
My api has a very simple code that returns a string and when I run my api, it works fine.
I have been struggling with this error for past 2 days. Any hint or help will be highly appreciated.
This is what I tried based on the answer below Still getting the same error:
services.AddCors(options =>
{
options.AddPolicy("CorsPolicy",
builder =>
{
builder.WithOrigins(new string[] { "http://localhost:4200" , "https://localhost:44378/api/offrec" }).AllowAnyMethod().WithHeaders("Access-Control-Allow-Origin:*");
});
});
below is the image of the error:
below is my api:
namespace RecLoad.Controllers
{
[Route("api/[controller]")]
[EnableCors("AllowAnyCorsPolicy")]
[HttpGet]
public ActionResult<string> Get()
{
return "This is a test";
}