2016-09-23 48 views
0

我想让CORS使用新的WebAPI项目。该项目只是使用ActiveDirectoryBearerAuthentication的默认WebAPI模板(即具有MVC和WebAPI参考)。使用WebAPI启用CORS

每当我试图让我的API请求,我遇到了以下错误:

XMLHttpRequest cannot load https://localhost:44385/api/values. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://localhost:44369' is therefore not allowed access.

我已经安装Microsoft.Owin.Cors和Microsoft.AspNet.WebApi.Cors。

我WebApiConfig是这样的:

public static void Register(HttpConfiguration config) 
{ 
    config.EnableCors(); 
    .... 

我Startup.Auth是这样的:周围的净

public void ConfigureAuth(IAppBuilder app) 
{ 
    app.UseCors(CorsOptions.AllowAll); 

    app.UseWindowsAzureActiveDirectoryBearerAuthentication(
    .... 

解决方案说补充:

<customHeaders> 
     <!-- Adding the following custom HttpHeader will help prevent CORS from stopping the Request--> 
     <add name="Access-Control-Allow-Origin" value="*" /> 
    </customHeaders> 

到web.config 。但是,这样做只是允许所有内容,而不管Microsoft.AspNet.WebApi.Cors是否已安装,启用或不可用。

+0

难道你不希望你允许一切,或者你仍然想限制访问和阻止一些其他请求 –

+0

有一点要知道的是,IE需要在响应中包含P3P头以便CORS工作 – pm100

+0

我想阻止除一个域之外的所有内容。我以为我会倒退,以确保它正在工作。如果我没有做到这一点,我会认为web.config解决方案解决了它 - 它不是只是允许所有的东西,无论CORS配置。 – Mardoxx

回答

0

只允许单个域,你可以做到以下几点:

<system.webServer> 
<httpProtocol> 
    <customHeaders> 
    <remove name="X-Powered-By" /> 
    <clear /> 
    <add name="Access-Control-Allow-Origin" value="http://www.myalloweddomain.com" /> 
    </customHeaders> 
</httpProtocol> 
</system.webServer> 

不过,如果是只允许单个域。如果您尝试添加额外的添加节点,您的网站将无法加载。如果你想允许多个域名,那么你需要尝试列出的解决方案之一here

+0

我试过这个,它的工作原理,谢谢。但是CORS中间件又有什么意义呢? – Mardoxx

+0

我假设你是指你在代码中完成的部分?正如我在答复结束时所说的,web.config设置仅适用于单个域。代码解决方案允许多域名白名单。另外,有些人更喜欢在代码中而不是在web.config中提供解决方案。 – Necoras

0

检查事项:

  • Owin踢在IIS(确保你包括Microsoft.Owin.Host.SystemWeb)
  • 检查IIS不劫持您的要求IIS hijacks CORS Preflight OPTIONS request
  • 使用fiddler将OPTION请求直接发送到指定的URL(有时PREFLIGHT请求只是服务器返回的掩码500) - 浏览器不是很好处理该问题
+0

我会看看,谢谢。这篇帖子的答案是“......作为最后的手段......”,这将只允许每个主机和代码覆盖任何东西,当然? – Mardoxx