gpt4 book ai didi

Azure WebApp Cors 不添加 Cors header

转载 作者:行者123 更新时间:2023-12-01 09:28:37 25 4
gpt4 key购买 nike

我有一个 Owin WebAPI2 .NET 应用程序,托管在 Azure 中的 AppService 上。

我想使用 Azure 添加 CORS 支持 in this article 。看起来很简单,您只需将 Origin 站点添加到列表中,如下所示:http://screencast.com/t/r2ATq4u5

我现在希望响应 header 包含此允许的来源。

但是,当我使用 Fiddler 检查时,CORS header 不包含在响应 header 中: http://corstestqm.azurewebsites.net/breeze/restaurantsbreeze/basictest

我尝试过的步骤:

  • 从我的解决方案中删除了所有 CORS Nuget 库以及我的 API 项目中的所有 CORS 代码痕迹。
  • 部署到全新的 AppService
  • Enabled Owin Cors全部允许

这些都没有任何效果。 (即响应不包含 Azure 中指定的 CORS header )。

我在这里错过了一些非常基本的东西吗?

更新我把问题进一步简化:在VS2015中,我创建了一个新的API项目并将其推送到http://corstestbasicap2.azurewebsites.net/api/values/没有任何变化(即它不应该启用 CORS)。

然后我使用 Test-Cors tool来访问该 API。它没有按预期收到 CORS 错误。然后,我进入 Azure 并添加一个虚拟 URL(例如 http://www.example.com )并再次尝试 CORS 测试。它应该会失败,因为 Azure 应该只让 example.com 通过。不过,它工作得很好。

然后我edit CORS again in Azure并添加http://www.test-cors.org下面http://www.example.com (所以它应该让其中一个通过),现在 header 按预期返回 Access-Control-Allow-Origin:http://www.test-cors.org

但这没有意义吗?当“http://www.test-cors.org ”不在允许的起源中时,之前的调用肯定会失败吗?它似乎没有做任何有用的事情?!

最佳答案

您可以通过在 web.config 中添加以下配置来实现这些:

<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*"/>
<add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Accept,Authorization"/>
<add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS"/>
</customHeaders>
</httpProtocol>
</system.webServer>

在 global.asax 中:

protected void Application_BeginRequest()
{
if (Request.Headers.AllKeys.Contains("Origin") && Request.HttpMethod == "OPTIONS")
{
Response.Flush();
}
}

如果您想从门户进行控制,请查看以下图片:

注意,根据应用服务 CORS documentation您不能在一个 API 应用程序中同时使用 Web API CORS 和应用服务 CORS。您必须清理有关 Web API CORS 的项目

Don't try to use both Web API CORS and App Service CORS in one API app. App Service CORS will take precedence and Web API CORS will have no effect. For example, if you enable one origin domain in App Service, and enable all origin domains in your Web API code, your Azure API app will only accept calls from the domain you specified in Azure.

enter image description here

关于Azure WebApp Cors 不添加 Cors header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41541917/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com