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

我正在使用这里描述的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>

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

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

编辑2:成功!...我启用了跟踪并找到了错误

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

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


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

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

只需将这些添加到策略的允许标题中,一切都应该起作用。

链接地址: http://www.djcxy.com/p/82649.html

上一篇: CORS enabled Web API fails to add header

下一篇: Accessing a HashSet using the HashCode directly? (Java)