Fabián Montero
Fabián Montero

Reputation: 1784

Set CORS header in ASP.NET HTTP response

I'm trying to set headers for my HTTP response to include CORS header Access-Control-Allow-Origin in order for the response to be easily read by my Anguler.js web app.

To do that, I'm doing the following:

using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace tecboxapi777.Controllers
{

 public class WorkersController : ApiController
    {
        // GET: api/Worker
        [Route("api/Workers")]
        [HttpGet]
        public HttpResponseMessage Get()
        {
            HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created);
            response.Headers.NAME_OF_THE_HEADER = "Access-Control-Allow-Origin";

        }
    }
}

As you can see, I am unable to find the correct name for the CORS header. I've searched online but all I find is to use something similar to Access-Contro-Allow-Origin = "*" which doesn't even compile.

My question is: How do I properly set my CORS headers so that my Angular.JS webapp is able to read my response?

Currently Firefox's developer mode console returns the following message in whenever I try to do a GET request to my API:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://192.168.0.6:45455/api/Workers. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing)

Just for the sake of completeness, the Angular.JS code that does the GET request is the following:

posts: Observable<any>;
getPosts(){
    this.posts = this.http.get(this.ROOT_URL + '/api/Workers');
    console.log(this.posts);
}

EDIT: I accepted Sotiris Koukios-Panopoulos's answer because it's what I did to solve my problem and also it requires no installation of packages. Nevertheless, Manish's answer is the better answer and its the one you should follow if you care about whats considered standard.

It surprises me how everything, even adding headers to a response, requires a package in .NET...

Upvotes: 2

Views: 5511

Answers (4)

Dinesh Deshpande
Dinesh Deshpande

Reputation: 27

Add below lines of code in your web.config , it will resolve your problem

<system.webServer>
<httpProtocol>
      <customHeaders>
        <remove name="Access-Control-Allow-Origin" />
        <add name="Access-Control-Allow-Origin" value="*" />
        <add name="Access-Control-Allow-Headers" value="*" />
        <add name="Access-Control-Allow-Methods" value="GET, POST,PUT,DELETE, OPTIONS" />
      </customHeaders>
    </httpProtocol>
</system.webServer>

Upvotes: 0

Manish
Manish

Reputation: 6286

Use Microsoft CORS package and install the NuGet package.

Right click on the project -> Manage NuGet Packages...

Install the nuget package Microsoft.AspNet.WebApi.Cors

Cors Package

Then you can configure CORS support for Web API at three levels:

  1. Global level
  2. Controller level
  3. Action level

Example:

Global Level

App_Start/WebApiConfig.cs file

public static void Register(HttpConfiguration config)  
{  
    EnableCorsAttribute cors = new EnableCorsAttribute("*", "*", "GET,POST");  
    config.EnableCors(cors);  
} 

Controller level

using Microsoft.AspNet.WebApi.Cors
[EnableCors(origins: "*", headers: "*", methods: "*")]  
public class TestController : ApiController  
{  
} 

Action level

public class TestController : ApiController  
{  
    [EnableCors(origins: "*", headers: "*", methods: "*")]  
    // GET api/values  
    public IEnumerable<string> Get()  
    {  
        return new string[] { "value 1", "value 2" };  
    }  
}  

Similarly you could also disable cors for specific actions. Say you have enabled it at controller level but want to disable for few of the actions:

[DisableCors()]  
// GET api/values/5  
public string Get(int id)  
{  
    return "value";  
} 

Upvotes: 3

Afeef Janjua
Afeef Janjua

Reputation: 659

First Install the Microsoft.AspNetCore.Cors Nuget package

Then configure CORS in the ConfigureService method.

public void ConfigureServices(IServiceCollection services)
{
    services.AddCors(options => {
        options.AddPolicy("AllowMyOrigin",
        builder => builder.WithOrigins("http://example.com"));
    });
}

Then enable CORS using middleware in the Configure method.

public void Configure(IApplicationBuilder app)
{
    app.UseCors("AllowMyOrigin");
}

Enable CORS in .NET Core MVC by enabling it in Controllers or actions or globally

Enable on action method

[EnableCors("AllowMyOrigin")]
[Route("api/Workers")]
[HttpGet]
public HttpResponseMessage Get()
{
    // You don't need the following now
    // HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created);
    // response.Headers.<NAME OF THE HEADER> = "Access-Control-Allow-Origin"

}

Enable on api controller

[EnableCors("AllowMyOrigin")]
public class WorkersController : ApiController

Enable for the whole application by adding the following in startup.cs

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();
    services.Configure<MvcOptions>(options => {
        options.Filters.Add(new CorsAuthorizationFilterFactory("AllowMyOrigin"));
    });
}

Upvotes: 2

Sotiris Panopoulos
Sotiris Panopoulos

Reputation: 1613

You have two ways to do this.

  • Enable this using a response header just like you initially tried:

    Response.Headers.Add("Access-Control-Allow-Origin", "*");

  • Configure it globally and use it selectively in your Controllers/Actions.

    For this, you can use the guide in the official docs which can explain it more thoroughly than I ever could

Upvotes: 4

Related Questions