【发布时间】:2015-10-16 05:55:39
【问题描述】:
我将我的 web 和 api 项目都部署到了单独的 Azure webapps 中,并且正在努力解决 CORS 问题。在本地部署时一切正常,但一旦发布到 Azure 就不行了。
我正在使用两种不同的方法来启用 CORS,但似乎都无法解决我的问题。
可能的修复:
- 在我的 web.config 中,我为
<add name="Access-Control-Allow-Origin" value="*" />添加了一个 customHeader - 在 WebApiConfig.cs 的 Register 方法中,我将 enableCors 称为
var cors = new EnableCorsAttribute("*", "*", "*");config.EnableCors(cors);
参考上述两个修复的方案如下:
- 在没有使用 #1 或 #2 的情况下,每个服务器调用都会返回 no access-control-allow-origin 错误(预期)
- 同时使用 #1 和 #2 时,我收到一个错误,提示我使用相同的值启用了两次 CORS(预期)
- 如果我只使用 #1,我不会收到 CORS 错误,但每个 API 方法都会返回 405 not allowed 错误
- 如果我只使用 #2,每个 api 调用都会返回 no access-control-allow-origin 错误
问题:如何为托管在 Azure 中的 .NET Web Api 项目全局启用 CORS?
appstart和注册码:
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
public static void Register(HttpConfiguration config)
{
// Enable CORS
// TODO, * below is debug only
var cors = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(cors);
// Web API configuration and services
// Configure Web API to use only bearer token authentication.
config.SuppressDefaultHostAuthentication();
config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
【问题讨论】:
-
我选择了 #2 路线。确保 config.EnableCors(cors);是您在启动时调用的第一件事。这似乎对我有帮助。
-
@AndresCastro 感谢您的回复。在我的 Register 函数中,只有 #2 作为字面上的前两个语句,我在每个 API 调用上都收到 no access-control-allow-origin 错误:(
-
介意发布您的应用启动和注册代码吗?
-
@AndresCastro 绝对是,刚刚编辑到我的原始帖子中
标签: azure asp.net-web-api cors