Access to XMLHttpRequest from origin has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource
Solution 1
You need to enable CORS in your Web Api. The easier and preferred way to enable CORS globally is to add the following into web.config
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Content-Type" />
<add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
</customHeaders>
</httpProtocol>
</system.webServer>
Update:
In ASP.Net core we do not have web.config rather we have app.config file. You still need to have web.config you can add a Web configuration item template. You can use that like change the max file upload limit etc.
The web.config file is generated when you are publishing the project.
Solution 2
In .Net 5 we can achieve this by enabling following default policy in startup.cs
services.AddCors(options =>
{
options.AddDefaultPolicy(
builder =>
{
builder.WithOrigins("http://example.com",
"http://www.contoso.com");
});
});
Tahreem Iqbal
Updated on June 05, 2022Comments
-
Tahreem Iqbal almost 2 years
I have created an API project in MVC Core. In my controller I have added some APIs of GET and POST methods that work perfectly fine with Postman. But when I try calling them from my Angular App, they give me CORS error:
Access to XMLHttpRequest from origin has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource
I googled for solutions and found out that I needed to add CORS NuGet package. I did that, but the error is still there.
Following is my
Startup.cs
file code:using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.HttpsPolicy; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using webapp1.Model; namespace webapp1 { 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.AddControllers(); services.AddCors(options => { options.AddPolicy("AllowAnyOrigin", builder => builder .AllowAnyOrigin() .AllowAnyMethod() .AllowAnyHeader()); }); services.AddDbContext<TodoContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseHttpsRedirection(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); app.UseCors(options => options.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader()); } } }
And following is my
API Controller
:using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using webapp1.Model; namespace webapp1.Controllers { [ApiController] [Route("[controller]")] public class TodoController : ControllerBase { TodoContext _context; public TodoController(TodoContext context) { _context = context; } [HttpGet] public List<Todo> Get() { return _context.Todos.ToList(); } } }
-
Selaka Nanayakkara over 4 yearsWhat is this question has to do with angular tag?
-
yaxx over 4 yearsAngular normally run a web-pack dev-server which by default run on port 4200 and your server normally runs on a different port which only allow request from same origin thus same port that it's running so to make http request from your dev-server is a cross-origin request which will be block by your server. To solve this you need to allow cross-origin request from your server depending on what server you are using. but in Express you simply add this: const cors = require('cors'); app.use(cors({origin:"localhost:4200", credentials: true})) after installing cors package
-
-
Tahreem Iqbal over 4 yearsi removed CORS code from
Startup.cs
. Simply adding these settings in web.config worked.