Angular/C# CORS Issue

本文关键字:Issue CORS Angular | 更新日期: 2023-09-27 17:54:19

我的客户端托管在localhost:8080/,服务器托管在localhost:44302/

我正试图链接到我的后端,但我得到CORS问题。下面是我的Angular http请求

$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
});

在用c#编写的服务器端,我对响应

进行了以下设置
 Response.ContentType = "application/json";
 Response.AddHeader("Access-Control-Allow-Origin", "*");
 Response.AddHeader("Access-Control-Allow-Methods", "POST, OPTIONS");

即使设置了这些,我还是得到以下错误

XMLHttpRequest无法加载https://localhost:44302/some_uri。请求的文件中没有"Access-Control-Allow-Origin"标头资源。因此,不允许使用原产地"http://localhost:8080"访问。响应的HTTP状态码为400。

我错过了什么?

Angular/C# CORS Issue

你不需要从AngularJS发送任何额外的头文件。我们会自动为您提出飞行前申请。

要启用Web API中的所有跨域请求,您可以这样做:

  1. 安装NuGet包microsoft . asp.net . webapi . cors .
  2. 添加以下代码到WebApiConfig.cs:

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

充分了解CORS值得花几分钟的时间。我建议在这里阅读一个深入的教程:

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

在您的应用程序级服务器端执行此操作客户端应用程序无需更改

步骤1:Install-Package Microsoft.AspNet.WebApi.Cors

步骤2:从HttpConfiguration对象中你可以启用cors -适用于整个应用程序

public static void Register(HttpConfiguration config)
    {
        // New code
        config.EnableCors();
        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }

备用:

步骤3:到控制器添加以下属性-仅适用于TestController

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

示例:

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