启用CORS的Web API无法添加标头

时间:2014-11-17 18:05:30

标签: c# asp.net asp.net-web-api asp.net-web-api2

我正在使用here所述的DynamicPolicyProviderFactory。以下是我的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

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

我的申请设置已通过:

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

尽管有这些设置,但如果我从Access-Control-Allow-Originhttp://mg.domain1.com发出请求,则我的回复中不会显示http://localhost标头。我正在使用Web Api 2.2和Microsoft.AspNet.Cors 5.2.2。

编辑:我发现如果我在控制器上使用EnableCors属性,或者全局启用它(config.EnableCors(new EnableCorsAttribute("*", "*", "*"));)它就可以了,所以它必须是我的动态工厂。令人沮丧的是,DynamicPolicyProvider是从我正在使用的另一个项目中复制/粘贴的,可以正常工作。

编辑2 成功!...我已启用tracing并发现错误

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

所以我刚刚编辑了GetPolicyForControllerAndOrigin方法以允许它们。现在一切正常,除了我感到困惑,因为我没有必要在我的其他项目(我从中复制DynamicPolicyProviderFactory)中跳过这个箍。

1 个答案:

答案 0 :(得分:5)

在应用中启用tracing。你应该看到一个错误

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

只需将这些添加到策略的允许标头中,一切都应该有效。