Angular/C# CORS Issue

8.7k views Asked by At

I hosted my client on localhost:8080/ and server on localhost:44302/

I am trying to link to my backend, but I am getting CORS issue. Below is my Angular http request

$http.post(url, data, {
    headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                    'Access-Control-Allow-Origin': '*',
                    'Access-Control-Allow-Methods': 'POST, OPTIONS'
             }
}).success(function (response) {
  // rest of the code
}).error(function (err, status) {
  // rest of the code
});

On the server side which is written in C#, I have the following set on the response

 Response.ContentType = "application/json";
 Response.AddHeader("Access-Control-Allow-Origin", "*");
 Response.AddHeader("Access-Control-Allow-Methods", "POST, OPTIONS");

Even after setting these, I am getting the following error

XMLHttpRequest cannot load https://localhost:44302/some_uri. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access. The response had HTTP status code 400.

What am I missing?

2

There are 2 answers

1
SoftwareFactor On BEST ANSWER

You do not need to send any additional headers from AngularJS. Preflight request will be made for you automatically.

To enable all cross-origin requests in Web API, you can do this:

  1. Install NuGet package Microsoft.AspNet.WebApi.Cors.
  2. Add the following code to WebApiConfig.cs:

        var corsAttr = new EnableCorsAttribute("*", "*", "*");
        config.EnableCors(corsAttr);
    

Full understanding of CORS is worth a few minutes of time. I recommend reading an in-depth tutorial here:

http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api

0
prakash r On

Perform this in your application level server side No changes required in your client-side application

Step 1: Install-Package Microsoft.AspNet.WebApi.Cors

Step 2: From HttpConfiguration object you can enable cors - Applicable for the entire application

public static void Register(HttpConfiguration config)
    {
        // New code
        config.EnableCors();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }

Alternate :

Step 3: Go to controller add this below attribute - Applicable only to TestController

// Allow CORS for all origins. (Caution!)
[EnableCors(origins: "*", headers: "*", methods: "*")]

Example :

[EnableCors(origins: "http://mywebclient.azurewebsites.net", headers: "*", methods: "*")]
public class TestController : ApiController
{
    // Controller methods not shown...
}