Cors WebAPI上的问题 [英] Cors issues on WebAPI

查看:699
本文介绍了Cors WebAPI上的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在WebAPI上启用Cors

Enabling Cors on WebAPI

我在WebApiConfig.cs中设置了此设置

I have this set in WebApiConfig.cs

config.EnableCors();

这是我的属性设置为我的控制器方法:

and this is how my attribute is setup for my controller method:

[EnableCors("http://dev.example.com,http://personal.example.com,http://www.example.com", // Origin
                    "Accept, Origin, Content-Type, Options",                       // Request headers
                    "POST",                                                        // HTTP methods
                    PreflightMaxAge = 600                                          // Preflight cache duration
        )]

但是我还是得到一个错误:Access-Control-Allow-Origin 'header contains multiple values。

But I still get the error: "The 'Access-Control-Allow-Origin' header contains multiple values."

我还需要做什么来防止这种情况?我们必须允许所有三个领域。但前两个是最后一个的子域。

What else do I need to do to prevent this? We must allow from all three domains. but the first 2 are sub-domains of the last one.

推荐答案

您有任何选项设置到您的web.config文件为cors?即< add name =Access-Control-Allow-Originvalue =*/>

do you have any options set into your web.config file for cors ? i.e something like <add name="Access-Control-Allow-Origin" value="*"/>

如果是,请确保删除,并通过代码控制cors。

if yes make sure to remove that, and control the cors through the code only.

编辑这意味着你总是添加头到您的响应,无论请求命中的控制器,并且如果请求命中控制器与EnableCors属性,它将添加另一个头。如果你删除Application_BeginRequest()中的一个,它应该工作,但这意味着你需要装饰所有其他控制器的EnableCors属性,这在你的情况下可能是可以接受的,否则,你需要添加一个DelegateHandler,你可以检查请求并根据所请求的控制器设置cors。请查看此 http:// georgedurzi .com / implementation-cross-browser-cors-support-for-asp-net-web-api / 它可能有助于从DelegateHandlers开始。希望有所帮助。

well, that means that you always add the header to your response, no matter which controller the request hits, and in case the request hits the controller with the EnableCors attribute it will add another header. If you removed the one in the Application_BeginRequest() it should work, however that means that you need to decorate all other controllers with EnableCors attribute, which maybe acceptable in your case, otherwise, you need to add a DelegateHandler where you can check the request and set the cors depending on the requested controller. have a look at this http://georgedurzi.com/implementing-cross-browser-cors-support-for-asp-net-web-api/ it may help start with DelegateHandlers. Hope that helps.

这篇关于Cors WebAPI上的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆