支持Web API CORS无法添加页眉 [英] CORS enabled Web API fails to add header

查看:308
本文介绍了支持Web API CORS无法添加页眉的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是 DynamicPolicyProviderFactory 描述的此处。下面是我的DynamicPolicyProviderFactory版本:

I am using the DynamicPolicyProviderFactory as described here. Below is my version of the DynamicPolicyProviderFactory:

public class DynamicPolicyProviderFactory : ICorsPolicyProviderFactory
{
    private readonly HashSet<Regex> _allowed;

    public DynamicPolicyProviderFactory(IEnumerable allowedOrigins)
    {
        _allowed = new HashSet<Regex>();

        foreach (string pattern in allowedOrigins.Cast<string>()
            .Select(Regex.Escape)
            .Select(pattern => pattern.Replace("*", "w*")))
        {
            _allowed.Add(new Regex(pattern, RegexOptions.IgnoreCase));
        }

        if (_allowed.Count >= 1)
            return;

        //if nothing is specified, we assume everything is.
        _allowed.Add(new Regex(@"https://\w*", RegexOptions.IgnoreCase));
        _allowed.Add(new Regex(@"http://\w*", RegexOptions.IgnoreCase));
    }

    public ICorsPolicyProvider GetCorsPolicyProvider(HttpRequestMessage request)
    {
        var route = request.GetRouteData();
        var controller = (string)route.Values["controller"];
        var corsRequestContext = request.GetCorsRequestContext();
        var originRequested = corsRequestContext.Origin;
        var policy = GetPolicyForControllerAndOrigin(controller, originRequested);
        return new CustomPolicyProvider(policy);
    }

    private CorsPolicy GetPolicyForControllerAndOrigin(string controller, string originRequested)
    {
        // Do lookup to determine if the controller is allowed for
        // the origin and create CorsPolicy if it is (otherwise return null)

        if (_allowed.All(a => !a.Match(originRequested).Success))
            return null;

        var policy = new CorsPolicy();
        policy.Origins.Add(originRequested);
        policy.Methods.Add("GET");
        policy.Methods.Add("POST");
        policy.Methods.Add("PUT");
        policy.Methods.Add("DELETE");
        return policy;
    }
}

public class CustomPolicyProvider : ICorsPolicyProvider
{
    private readonly CorsPolicy _policy;

    public CustomPolicyProvider(CorsPolicy policy)
    {
        this._policy = policy;
    }

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

我的电话注册CORS赢得WebApiConfig.cs

My call to register the cors win the WebApiConfig.cs

 config.EnableCors();
 config.SetCorsPolicyProviderFactory(new DynamicPolicyProviderFactory(Settings.Default.AllowedDomains));

和我的应用程序设置被传递:

And my application settings being passed:

<MyApp.Properties.Settings>
  <setting name="AllowedDomains" serializeAs="Xml">
    <value>
      <ArrayOfString xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
        <string>http://localhost</string>
        <string>http*://*.domain1.com</string>
        <string>http*://*.domain2.com</string>
      </ArrayOfString>
    </value>
  </setting>
</MyApp.Properties.Settings>

尽管这些设置,访问控制允许来源头是不是对我的回答present如果我从的请求http://mg.domain1.com 的http://本地主机。我使用的Web API 2.2和5.2.2 Microsoft.AspNet.Cors

Despite these settings, the Access-Control-Allow-Origin header is not present on my responses if I make a request from http://mg.domain1.com to http://localhost. I am using Web Api 2.2 and Microsoft.AspNet.Cors 5.2.2.

编辑:我发现,如果我使用控制器上的 EnableCors 属性或全局启用它( config.EnableCors(新EnableCorsAttribute(*,*,*)); )它的工作原理,因此它必须是一些与我的动态工厂。令人沮丧的是,在DynamicPolicyProvider是复制/从另一个项目粘贴我使用的正常工作。

edit: I have found that if I use the EnableCors attribute on the controller, or enable it globally (config.EnableCors(new EnableCorsAttribute("*", "*", "*"));) it works, so it must be something with my dynamic factory. The frustrating thing is, the DynamicPolicyProvider is copy/pasted from another project I am using that works fine.

编辑2:成功......我启用的追踪并发现错误

edit 2: Success!...I enabled tracing and found the error

 The collection of headers 'accept,content-type' is not allowed

所以,我刚才编辑的 GetPolicyForControllerAndOrigin 方法,以允许他们。现在一切正常,请接受我很困惑,因为我没有在我的其他项目(一个我复制从DynamicPolicyProviderFactory)

So I just edited the GetPolicyForControllerAndOrigin method to allow them. Now everything works, accept I am confused because I did not have to jump through this hoop in my other project (the one I copied the DynamicPolicyProviderFactory from)

推荐答案

启用的在应用程序跟踪。你应该会看到一个错误

Enable tracing in the app. You should see an error

The collection of headers 'accept,content-type' is not allowed

只需添加这为政策允许的头,一切都应该工作。

Just add these to the allowed headers for the policy and everything should work.

这篇关于支持Web API CORS无法添加页眉的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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