Tahreem Iqbal
Tahreem Iqbal

Reputation: 1015

Access to XMLHttpRequest from origin has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource

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();
        }
    }
}

Upvotes: 3

Views: 28715

Answers (2)

rajquest
rajquest

Reputation: 711

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");
            });
    });

Upvotes: 1

Naila Akbar
Naila Akbar

Reputation: 3358

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.

Upvotes: 7

Related Questions