How to Enable Cross-Origin Requests (CORS) in ASP.NET Core

How to Enable Cross-Origin Requests (CORS) in ASP.NET Core

Browser security prevents a web page located on a domain to make requests to a web page which is located on a different domain. This restriction is called the same-origin policy.

For example suppose I have a web page called A.html in my website. It’s URL being:

https://www.yogihosting.com/A.html

Now page A.html has an AJAX code that tries to read the HTML source code of another page B.html, but B.html is located on a different domain with it’s URL as:

http://www.asp.net/B.html
Due to B.html located in a different domain, the page A.html will not be able to make AJAX request due to the restriction called same-origin policy.

The AJAX call will return the error message:

No ‘Access-Control-Allow-Origin’ header is present on the requested resource.

Thankfully there is Cross Origin Resource Sharing (CORS) which is a W3C standard that allows browsers to relax the same-origin policy.

So if the website asp.net implements CORS then my website’s page called A.html will be able to make successful AJAX request to B.html and can get B’s HTML source code by using AJAX.

How Does CORS Work?

Once a website enables CORS, new HTTP headers are introduced which enable cross-origin requests. These HTTP headers are automatically set for cross-origin requests. One important HTTP header is called Access-Control-Allow-Origin. So when an external page or resource, makes requests to a resource (like a page, file, etc) on another Server or domain, then this server responds with a value for the Access-Control-Allow-Origin header.

Many times, this value will be *, meaning that Server will share the requested resources with any domain on the Internet. Other times, the value of this header may be set to a particular domain (or list of domains), meaning that Server will share its resources with that specific domain (or list of domains).

And in this way CORS works to relax the same-origin policy.

Enable CORS in ASP.NET Core

An ASP.NET Core website can enable CORS quite easily. You just need to follow below steps:
  • 1. Install the Microsoft.AspNetCore.Cors Nuget package.
  • 2. Register CORS in the ConfigureService() method of Startup.cs.
  • 3. Enable CORS using middleware in the Configure() method of Startup.cs.

Install CORS NuGet Package

To install Microsoft.AspNetCore.Corspackage, run the following command in the Package Manager Console window:
PM> Install-package Microsoft.AspNetCore.Cors
Alternately, you can also install it by going to NuGet Package Manager > Manage NuGet Packages for Solution in your Visual Studio. Then go to the ‘Browse’ tab and search CORS in the text box.
CORS package in NuGet

Register CORS

You need to Register CORS service in the Startup.cs file’s ConfigureServices() method as shown below:
public void ConfigureServices(IServiceCollection services)
{
    services.AddCors();
    services.AddControllersWithViews();
}

Enable CORS using middleware

Next you need to add the CORS middleware to your app. In your Startup.cs you should have a Configure() method. You need to have it similar to this:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseExceptionHandler("/Home/Error");
        app.UseHsts();
    }

    app.UseHttpsRedirection();

    // Shows UseCors with CorsPolicyBuilder.
    app.UseCors(builder =>
    {
        builder
        .AllowAnyOrigin()
        .AllowAnyMethod()
        .AllowAnyHeader();
    });

    app.UseStaticFiles();

    app.UseRouting();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllerRoute(
            name: "default",
            pattern: "{controller=Home}/{action=Index}/{id?}");
    });
}
Notice I added the code line with the option AllowAnyOrigin to accept any domain that makes CORS request:
app.UseCors(builder =>
{
    builder
    .AllowAnyOrigin()
    .AllowAnyMethod()
    .AllowAnyHeader();
});

I have also used other method which are described below:

  • 1. AllowAnyMethod() – To allow all HTTP methods.
  • 2. AllowAnyHeader() – To allow all request headers.
  • 3. AllowCredentials() – the server must allow the credentials.

If you want to enable CORS for request made from 1 domain only like https://www.yogihosting.com then change the above code to:

app.UseCors(builder =>
{
    builder
    .WithOrigins("https://www.yogihosting.com")
    .AllowAnyMethod()
    .AllowAnyHeader()
    .AllowCredentials();
});

You can specify more than 1 domains like this:

app.UseCors(builder =>
{
    builder
    .WithOrigins(new string[] { "https://www.yogihosting.com", "https://example1.com", "https://example2.com" })
    .AllowAnyMethod()
    .AllowAnyHeader()
    .AllowCredentials();
});
Want to build high quality APIs? Check – How to Consume ASP.NET Core API in jQuery

Apply CORS policies per action or per controller

Define one or more named CORS policies and select the policy by name at runtime. See the following example which adds a user-defined CORS policy named as MyPolicy.

To select the policy, pass the name to the UseCors() method:
public void ConfigureServices(IServiceCollection services)
{
    services.AddCors(options =>
    {
        options.AddPolicy("MyPolicy",
            builder => builder.WithOrigins("https://www.yogihosting.com"));
    });

    services.AddControllersWithViews();
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseExceptionHandler("/Home/Error");
        app.UseHsts();
    }

    app.UseHttpsRedirection();

    // Shows UseCors with named policy.
    app.UseCors("MyPolicy");

    app.UseStaticFiles();

    app.UseRouting();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllerRoute(
            name: "default",
            pattern: "{controller=Home}/{action=Index}/{id?}");
    });
}

Now you can apply this CORS policy per action or per controller.

Per Action

To specify a CORS policy for a specific action, add the [EnableCors] attribute of Microsoft.AspNetCore.Cors namespace to the action and specify the policy name:
[EnableCors("MyPolicy")]
public IEnumerable<string> Get()
{
    return new string[] { "value1", "value2" };
}

Per controller

[EnableCors("MyPolicy")]
public class HomeController : Controller 
To disable CORS for a controller or action, use the [DisableCors] attribute:
[DisableCors]
public string Get(int id)
{
    return "value";
}

The link to download the full source code of this tutorial is given below:

Download

Conclusion

I hope you loved this tutorial on CORS in ASP.NET Core. Please share it on your Facebook and Twitter accounts. Also check my other related tutorial given in the below section.

Share this article -

yogihosting

ABOUT THE AUTHOR

This article has been written by the Technical Staff of YogiHosting. Check out other articles on "ASP.NET Core, jQuery, EF Core, SEO, jQuery, HTML" and more.

Leave a Reply

Your email address will not be published. Required fields are marked *