【发布时间】:2015-11-24 18:11:14
【问题描述】:
我在 Web API 中启用了 CORS 时遇到问题。对服务器的 OPTIONS 请求正在返回正确的 CORS 标头。但是,如果我更改 API 的 web.config 中的任何内容,则不会返回 CORS 标头 访问控制允许来源:“*”。
要让 Web.API 再次工作,我必须对 web.config 进行更改。重新编译我的 web api 并使用不同的版本号进行部署,然后 api 将在 OPTIONS 飞行前检查期间运行并返回我的 CORS 标头
编辑:添加注册和启用 cors 的代码 Global.asax.cs:
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
log4net.Config.XmlConfigurator.Configure();
}
在 WebApiConfig.cs 中:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.EnableCors();
config.Formatters.JsonFormatter.
SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
config.MapHttpAttributeRoutes();
config.Services.Add(typeof(IExceptionLogger), new GlobalExceptionLogger());
config.Services.Replace(typeof(IExceptionHandler), new GlobalExceptionHandler());......
除此之外......我离开办公室时让 API 保持运行......然后几个小时后 API 再次停止工作,而无需进行任何更改。我在这里猜测,但是当应用程序池回收或 CORS 和路由的配置在回收后被遗忘等时,似乎没有调用 application_Start 例程......
【问题讨论】:
-
你能显示启用 CORS 的代码吗?
标签: .net rest asp.net-web-api