加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 07:56:03 所属栏目:百科 来源:网络整理
导读:我正在使用如 here所述的DynamicPolicyProviderFactory.下面是我的DynamicPolicyProviderFactory版本: public class DynamicPolicyProviderFactory : ICorsPolicyProviderFactory{ private readonly HashSetRegex _allowed; public DynamicPolicyProviderFa
我正在使用如 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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读