Enable CORS in Asp .Net 5(vNext) and MVC 6

Before going for the basic question “What is CORS?”, Let us take a scenario related to that.

Let us start from very basic example.

Suppose there are 2 URLs which are as below:

http://Alphabet.com/abc.html
http://Alphabet.com/xyz.html

Here above both URLs looks almost same so let us call it “same origin”.

Now, after making little twist we are having some more URLs as below:

http://Alphabet.in //// You are having different domain.
http://www.Alphabet.com/xyz.html //// You have different sub domain
http://Alphabet.com:7000/abc.html //// Oh man you are having different ports

So, as we have seen in above examples URLs does not look similar so let us call it “Different origin”.

Now let us create an Ajax request to some random site like http://Alphabet.com using this jsfiddle :

 $(document).ready(function() { 
    $.ajax({ url: "http://www.Alphabet.com", success: function(data){
        alert(data); 
    } 
   });
 });

And in response you will get:

XMLHttpRequest cannot load http://www.alphabets.com/. No ‘Access-Control-Allow-Origin’ header is present on the requested resource. Origin ‘http://fiddle.jshell.net’ is therefore not allowed access.

Why??

Because Browser security prevents a web page from making AJAX requests to another domain. This restriction is called the same-origin policy, and prevents a malicious site from reading sensitive data from another site.

Now let us just call(Well not just call but scream) our savior which is CORS!!!!!

56563147

Now the question which we left in starting arrives like, “What is CORS?”

CORS stands for Cross Origin Resource Sharing.

CORS is a W3C standard that allows a server to relax the same-origin policy. Using CORS, a server can explicitly allow some cross-origin requests while rejecting others.

Till now I hope you would have understood what CORS is all about.

Great! Coming to .Net, Does .Net supports CORS?

Yes, It surely does.

To install Microsoft ASP.NET Cross-Origin Support, run the following command in the Package Manager Console:

CORS

How to configure CORS in .Net 5?

First of all we will add CORS service in Startup.cs file as below:

public void ConfigureServices(IServiceCollection services)
{
   services.AddCors();
}

Then You have to configure a CORS policy at application startup in the ConfigureServices method:

public void ConfigureServices(IServiceCollection services)
{
    services.AddCors();
    services.ConfigureCors(options => options.AddPolicy("AllowAll", p => p.AllowAnyOrigin()
                                                                        .AllowAnyMethod()
                                                                         .AllowAnyHeader());
}

NOTE: In my example i have taken a configuration policy which allows pretty much everyhing with the name “AllowAll”

Next step would be to apply our settings to our controller actions.

For that there are mainly 2 options:

  • Use this in your attribute on controller actions:
    [EnableCors("AllowAll")]
  • Configure it for every request at application startup:
public void Configure(IApplicationBuilder app)
{
    app.UseCors("AllowAll");
}

Now Suppose we have below 2 projects.

http://www.ConsumeMe.com (has a ASP.NET WebAPI available)
http://www.UseMeToConsume.com

And our ConsumeMe project is having an action method as below:

public class DemoController : Controller
{
    [EnableCors("AllowAll")]
    public string Get()
    {
        return "CORS, You are working!";
    }
}

Let us make an Ajax call from UseMeToConsume to check:

$.ajax({
   url: "http://localhost:1400/api/demo",
   type: "GET",
   success: function (data) {
       alert(data);
   },
   error: function (event) {
       alert("Error!");
   }
});

And thanks to our CORS you will get:

“CORS, You are working!”

There are different options which can be used within CORS.

So i would request to give a look here for more information about different options of CORS in .Net:

Nuget URL for CORS is here

Stay tuned for more updates!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s