简体   繁体   English

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

[英]CORS enabled Web API fails to add header

I am using the DynamicPolicyProviderFactory as described here . 我正在使用此处描述的DynamicPolicyProviderFactory Below is my version of the 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);
    }
}

My call to register the cors win the WebApiConfig.cs 我注册cors的电话赢得了WebApiConfig.cs

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

And my application settings being passed: 我的应用程序设置被传递:

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

Despite these settings, the Access-Control-Allow-Origin header is not present on my responses if I make a request from http://mg.domain1.com to http://localhost . 尽管有这些设置,但如果我从http://mg.domain1.comhttp://localhost发出请求,则我的响应中不会出现Access-Control-Allow-Origin标头。 I am using Web Api 2.2 and Microsoft.AspNet.Cors 5.2.2. 我正在使用Web Api 2.2和Microsoft.AspNet.Cors 5.2.2。

edit: I have found that if I use the EnableCors attribute on the controller, or enable it globally ( config.EnableCors(new EnableCorsAttribute("*", "*", "*")); ) it works, so it must be something with my dynamic factory. 编辑:我发现如果我在控制器上使用EnableCors属性,或者全局启用它( config.EnableCors(new EnableCorsAttribute("*", "*", "*")); )它可以工作,所以它必须是与我的动态工厂有关。 The frustrating thing is, the DynamicPolicyProvider is copy/pasted from another project I am using that works fine. 令人沮丧的是,DynamicPolicyProvider是从我正在使用的另一个项目中复制/粘贴的。

edit 2: Success!...I enabled tracing and found the error 编辑2:成功!...我启用了跟踪并发现了错误

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

So I just edited the GetPolicyForControllerAndOrigin method to allow them. 所以我只是编辑了GetPolicyForControllerAndOrigin方法来允许它们。 Now everything works, except I am confused because I did not have to jump through this hoop in my other project (the one I copied the DynamicPolicyProviderFactory from). 现在一切正常,除了我感到困惑,因为我没有必要跳过我的另一个项目(我从中复制DynamicPolicyProviderFactory)。

Enable tracing in the app. 在应用中启用跟踪 You should see an error 你应该看到一个错误

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

Just add these to the allowed headers for the policy and everything should work. 只需将这些添加到策略的允许标头中,一切都应该有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 带有自定义标头的Ajax请求已发送到启用了CORS的Web API服务器 - Ajax request with custom header sent to Web API server with CORS enabled c#已启用CORS的Web Api和所请求资源上存在可怕的“Access-Control-Allow-Origin”标头 - c# Web Api with CORS Enabled and the dreaded No 'Access-Control-Allow-Origin' header is present on the requested resource Angular 6 Asp.Net(非核心)Web Api CORS 请求失败 - Angular 6 Asp.Net (not Core) Web Api CORS request fails Web API 2 CORS不存在“ Access-Control-Allow-Origin”标头 - web api 2 CORS No 'Access-Control-Allow-Origin' header is present CORS 带有启用选项 Header on ASP Net Core 5 Web Z72664DC0959F877C043891 - CORS With Enable OPTIONS Header on ASP Net Core 5 Web Api 在 .NET 核心 Web API 上为 CORS 启用选项 header - Enable OPTIONS header for CORS on .NET Core Web API 使用 Windows 身份验证的已启用 CORS ASP.NET Web API 2 应用程序中的预检请求 - preflight request in enabled CORS ASP.NET Web API 2 application with windows authentication 仅当启用cors时,asp.net Web API POST请求的400响应 - 400 Response for asp.net web api POST request only when cors is enabled Web API CORS实施 - Web API CORS implementation 在Web Api 2中启用CORS - Enabling CORS in Web Api 2
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM