微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

原文地址:https://www.jb51.cc/csharp/100002.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐