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

前端之家收集整理的这篇文章主要介绍了c# – 启用CORS的Web API无法添加标头前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在使用如 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>

尽管有这些设置,但如果我从http://mg.domain1.com向http:// localhost发出请求,则我的响应中不会出现Access-Control-Allow-Origin标头.我正在使用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).

解决方法

在应用中启用 tracing.你应该看到一个错误
The collection of headers 'accept,content-type' is not allowed

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

原文链接:/csharp/100002.html

猜你在找的C#相关文章