的ASP.NET Web API CORS不是AngularJS工作 [英] ASP.NET Web API CORS not working with AngularJS

查看:191
本文介绍了的ASP.NET Web API CORS不是AngularJS工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些端口上本地运行一个ASP.NET Web API和我有8080运行我想从客户端访问该API的应用程序angularjs

I have an ASP.NET Web API running locally on some port and I have an angularjs app running on 8080. I want to access the api from the client.

我可以成功登录并注册我的应用程序,因为在我的OAuthAuthorizationProvider明确设置repsonse头在/令牌端点。

I can successfully login and register my application because in my OAuthAuthorizationProvider explicitly sets the repsonse headers in the /Token endpoint.

    public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
    {
        context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });

这是很好的。然而,似乎我的其他API方法并不管用。在我WebApiCongig.Register,启用CORS和我添加EnableCors属性我控制器允许所有来源,所有的标题,和所有的方法。我可以设置在控制器上我get方法一个破发点,它被击中就好了。以下是我发现看在Chrome网络选项卡。

That's good. However, my other API methods do not seem to work. In my WebApiCongig.Register, I enable CORS and I add the EnableCors Attribute to my controllers to allow all origins, all headers, and all methods. I can set a break point in my get method on the controller and it gets hit just fine. Here is what I found watching the Network tab in chrome.

2请求被发送到同一个API方法。一种方法类型选项和一个与方法类型GET。 OPTIONS请求头包含以下两行

2 requests are are sent to the same api method. One method type OPTIONS and one with method type GET. The OPTIONS request header includes these two lines

访问控制请求报头:接受,授权

Access-Control-Request-Headers:accept, authorization

访问控制请求-方法:GET

Access-Control-Request-Method:GET

和响应包括这些行

接入控制允许头:授权

访问控制允许来源:*

Access-Control-Allow-Origin:*

不过,GET方法请求看起来完全不同。它返回OK用的状态代码200,但它不存在于请求或响应inlcude和访问控制报头。就像我说的,它击中API就好了。我甚至可以做一个POST并保存到数据库中,但客户抱怨的响应!

However, the GET method request looks quite different. It returns ok with a status code of 200, but it does not inlcude and access control headers in the request or response. And like I said, it hits the API just fine. I can even do a POST and save to the database, but the client complains about the response!!

我看着每一个SO问题,并试图的每个组合使CORS。我使用Microsoft.AspNet.Cors版本5.2.2。我使用AngularJS版本1.3.8。我还使用了$资源服务,而不是HTTP $这似乎不有所作为无论是。

I've looked at every single SO question and tried every combination of enabling cors. I'm using Microsoft.AspNet.Cors version 5.2.2. I'm' using AngularJS version 1.3.8. I'm also using the $resource service instead of $http which doesn't seem to make a difference either.

如果我可以提供更多信息,请让我知道

If I can provide more information, please let me know.

顺便说一句,我可以访问使用招和/或邮差简单的包含承载令牌的Web API。

BTW, I can access the Web API using Fiddler and/or Postman by simply including the Bearer token.

推荐答案

这最终是一个简单的修复。很简单,但它仍然无法从我的额头上瘀伤带走。这似乎是更简单,更令人沮丧的。

This ended up being a simple fix. Simple, but it still doesn't take away from the bruises on my forehead. It seems like the more simple, the more frustrating.

我创建自己的自定义CORS策略提供者的属性。

I created my own custom cors policy provider attribute.

public class CorsPolicyProvider : Attribute, ICorsPolicyProvider
{
    private CorsPolicy _policy;

    public CorsPolicyProvider()
    {
        // Create a CORS policy.
        _policy = new CorsPolicy
        {
            AllowAnyMethod = true,
            AllowAnyHeader = true,
            AllowAnyOrigin = true
        };

       // Magic line right here
        _policy.Origins.Add("*");

    }

    public Task<CorsPolicy> GetCorsPolicyAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        return Task.FromResult(_policy);
    }
}



我这个打了好几个小时。一切都应该工作的权利?我的意思是EnableCors属性应太?但事实并非如此。所以,我最后补充道上面一行到原点明确地添加到策略。 BAM!像变魔术一样。要使用该只属性添加到您的API类或您希望允许的方法。

I played around with this for hours. Everything should work right?? I mean the EnableCors attribute should work too?? But it didn't. So I finally added the line above to explicitly add the origin to the policy. BAM!! It worked like magic. To use this just add the attribute to your api class or method you want to allow.

[Authorize]
[RoutePrefix("api/LicenseFiles")]
[CorsPolicyProvider]
//[EnableCors(origins: "*", headers: "*", methods: "*")] does not work!!!!!  at least I couldn't get it to work
public class MyController : ApiController
{

这篇关于的ASP.NET Web API CORS不是AngularJS工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆