我在网络API项目中非常努力地理解和启用CORS。我遇到了阻塞点。我开始使用带有ASP.NET标识的ASP.NET MVC Web Api 2项目。无论我做什么似乎都行不通。
我删除了我的global.asx
文件,我的初创公司看起来像这样:
public partial class Startup
{
public void Configuration(IAppBuilder app)
{
HttpConfiguration configuration = new HttpConfiguration();
// I'm not sure it this is the proper way to use webapiconfig
WebApiConfig.Register(configuration);
app.UseWebApi(configuration);
app.UseCors(CorsOptions.AllowAll);
ConfigureAuth(app);
}
}
和WebApiConfig.Register代码是:
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Configure Web API to use only bearer token authentication.
config.SuppressDefaultHostAuthentication();
config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
config.AddODataQueryFilter();
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
var jsonFormatter = config.Formatters.OfType<JsonMediaTypeFormatter>().First();
jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
RegisterModels(); //Automapper here
}
我安装了mc aspnet cors和microsoft owin主机系统web。
&#34; [assembly:OwinStartup(typeof(MyProject.Startup))]&#34;已经到位,并在web.config
我有:
<appSettings>
<add key="owin:AutomaticAppStartup" value="true" />
</appSettings>
我只调用app.UseCors(CorsOptions.AllowAll)启用CORS,没有其他方式如config.enableCors
或其他任何方式,但每当我尝试获取API中的令牌或任何内容时,我都会收到错误:< / p>
原因:缺少CORS标题“Access-Control-Allow-Origin”。
我已经尝试在Configuration
方法中设置一个断点,但它并没有被调用。我正在使用IIS Express进行调试。
答案 0 :(得分:5)
对我来说没有任何作用......经过多次尝试,我终于成功了。
如果您遇到同样的问题..
1)从安装的金块包中删除与cors相关的任何内容..一切。
2)从web.config中删除与cors相关的任何内容。
3)在Gloabal.asax
protected void Application_BeginRequest(object sender, EventArgs e)
{
var context = HttpContext.Current;
var response = context.Response;
response.AddHeader("Access-Control-Allow-Origin", "*");
response.AddHeader("X-Frame-Options", "ALLOW-FROM *");
if (context.Request.HttpMethod == "OPTIONS")
{
response.AddHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PATCH, PUT");
response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
response.AddHeader("Access-Control-Max-Age", "1000000");
response.End();
}
}
这对/ api和/ token都有效。 这是一个通用的解决方案,请在将其部署到prod之前注意。
希望能帮助任何有同样问题的人。