Angular/C# CORS Issue

妖精的绣舞 提交于 2021-01-27 21:27:27

问题


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?


回答1:


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




回答2:


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...
}


来源:https://stackoverflow.com/questions/30720303/angular-c-cors-issue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!