21

我有两个 VS 项目:一个公开 MVC5 控制器,另一个是 Angular 客户端。我希望角度客户端能够查询控制器。我阅读了许多线程并尝试了以下方法:

  • 我在服务器的网络配置中添加了这个:

    <system.webServer>
        <httpProtocol>
           <customHeaders>
                <clear />
                <add name="Access-Control-Allow-Origin" value="*" />
            </customHeaders>
        </httpProtocol>
    <system.webServer>
    
  • 我在控制器的操作上创建并使用了以下过滤器:

    public class AllowCrossSiteJsonAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            filterContext.RequestContext.HttpContext.Response.AddHeader("Access-Control-Allow-Origin", "*");
            base.OnActionExecuting(filterContext);
        }
    }
    
  • 在 Angular 客户端中,我创建了以下拦截器:

    app.factory("CORSInterceptor", [
        function()
        {
            return {
                request: function(config)
                {
                     config.headers["Access-Control-Allow-Origin"] = "*";
                     config.headers["Access-Control-Allow-Methods"] = "GET, POST, OPTIONS";
                     config.headers["Access-Control-Allow-Headers"] = "Content-Type";
                     config.headers["Access-Control-Request-Headers"] = "X-Requested-With, accept, content-type";
                     return config;
                }
         };
    }
    ]);
    
    app.config(["$httpProvider", function ($httpProvider) {
        $httpProvider.interceptors.push("CORSInterceptor");
    }]);
    

根据 Firebug,这会导致以下请求:

OPTIONS //Login/Connect HTTP/1.1
Host: localhost:49815
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:40.0) Gecko/20100101 Firefox/40.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Origin: http://localhost:50739
Access-Control-Request-Method: POST
Access-Control-Request-Headers: access-control-allow-headers,access-control-allow-origin,content-type
Connection: keep-alive
Pragma: no-cache
Cache-Control: no-cache

以及以下回应:

HTTP/1.1 200 OK
Allow: OPTIONS, TRACE, GET, HEAD, POST
Server: Microsoft-IIS/10.0
Public: OPTIONS, TRACE, GET, HEAD, POST
X-SourceFiles: =?UTF-8?B?RDpcVEZTXElVV2ViXEdhcE5ldFNlcnZlclxBU1BTZXJ2aWNlc1xMb2dpblxDb25uZWN0?=
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET, POST, OPTIONS
Access-Control-Allow-Headers: *
Access-Control-Request-Headers: X-Requested-With, accept, content-type
Date: Tue, 01 Sep 2015 13:05:23 GMT
Content-Length: 0

而且,Firefox 仍然使用以下消息阻止请求:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:49815//Login/Connect. (Reason: missing token 'access-control-allow-headers' in CORS header 'Access-Control-Allow-Headers' from CORS preflight channel).
4

3 回答 3

30

通常,我阅读的线程会建议几个不必要的配置步骤,这会造成混乱。其实很简单...

出于将跨站点请求从 Angular 客户端发送到 ASP 控制器的简单目的:

  • 不需要角度拦截器。
  • 服务器端不需要自定义过滤器。
  • 唯一的强制修改是在服务器的 web.config 中添加它

    <system.webServer>
          <httpProtocol>
              <customHeaders>
                  <clear />
                  <add name="Access-Control-Allow-Origin" value="*" />
                  <add name="Access-Control-Allow-Headers" value="Content-Type"/>
              </customHeaders>
         </httpProtocol>
    </system.webServer>
    
于 2015-09-02T09:44:40.407 回答
17

问题是,一些浏览器还不允许*. Access-Control-Allow-Headers具体来说,Firefox 69 和更早版本没有。请参阅https://bugzilla.mozilla.org/show_bug.cgi?id=1309358

因此,为了确保您在所有浏览器中获得正确的行为,Access-Control-Allow-Headers您发回的值应该明确列出您实际需要从前端代码访问的所有标头名称;例如,在问题的情况下:Access-Control-Allow-Headers: Content-Type

无需对所有标头名称进行硬编码即可实现此目的的一种方法是:让您的服务器端代码获取Access-Control-Request-Headers浏览器发送的请求标头的值,然后将其回显到Access-Control-Allow-Headers服务器发回的响应标头的值中。

或者使用一些现有的库来启用你的服务器。将Access-Control-Request-Headersrequest-header 值回显到Access-Control-Allow-Headersresponse-header 值是大多数 CORS 库通常会为您做的事情。

于 2015-09-02T07:01:19.920 回答
0

我在 Angular 8 中尝试了我的 .net c# mvc 应用程序和客户端应用程序,但它不起作用。在 web.config 中,我添加了

<httpProtocol>
  <customHeaders>
    <clear />
    <add name="Access-Control-Allow-Origin" value="http://localhost:4200" />
    <add name="Access-Control-Allow-Headers" value="Content-Type"/>
  </customHeaders>
</httpProtocol>

在 global.axax.cs 文件中,我也添加了

    void MvcApplication_AuthenticateRequest(object sender, EventArgs e)
    {
        Context.Response.AddHeader("Access-Control-Allow-Origin", "http://localhost:4200");
    }

但它不工作。在响应标头中的 chrome 中,它确实显示为:

访问控制允许标题:内容类型访问控制允许来源:http://localhost:4200 访问控制允许来源:http://localhost:4200

但在请求标头中显示为

访问控制请求标头:访问控制允许来源、内容类型、x-iphoneclientid

而它需要像

x-iphoneclientid : 8E72FF50-548B

因为 x-iphoneclientid 是我在过滤器类中验证的令牌

    protected override System.Threading.Tasks.Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)
    {

        if (request == null || request.RequestUri == null)
        {
            return null;
        }
        // Write your Authentication code here
        IEnumerable<string> monsterApiKeyHeaderValues = null;

        // Checking the Header values
        if (request.Headers.TryGetValues("x-iphoneclientid", out monsterApiKeyHeaderValues))

并且没有找到上述条件,因此它拒绝它并且它没有到达控制器。

我什至在我的控制器中添加了以下内容

[启用Cors(“ ”,“ ”,“*”)]

你能指导一下吗

谢谢

于 2019-11-08T06:50:49.453 回答