我很努力地理解和启用一个web api项目中的CORS。我遇到了阻碍点。我已经开始使用ASP.NET身份的ASP.NET MVC Web Api 2项目。无论我做什么似乎都行不通。Cors不工作在web api 2.0
我已经删除了我的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和微软owin主机系统网站已安装。 的 “[组件:OwinStartup(typeof运算(MyProject.Startup))]” 代替,并在web.config
我有:
<appSettings>
<add key="owin:AutomaticAppStartup" value="true" />
</appSettings>
我只调用app.UseCors(CorsOptions.AllowAll)使CORS,像config.enableCors
或其他任何东西,但每当我试图获得API令牌或任何没有其他办法,我得到的错误:
Reason: CORS header ‘Access-Control-Allow-Origin’ missing.
我试图把在Configuration
方法中设置断点,但它不叫。 ..永远。我正在使用IIS Express进行调试。
这是唯一对我有用的解决方案。谢谢! – alvipeo
非常感谢,关于生产部署应采取的任何建议? – Lobato
嗨洛巴托,如果你知道你的电话来自哪里然后改变*与该网站的起源。因为*现在意味着'Anywhere'。此外,某些apis只允许来自外部的“GET”,您必须使用他们的工具进行CRUD操作。您可以忽略更改'Access-Control-Max-Age',因为它将被浏览器特定的值覆盖。 (在Chrome中为10分钟)。 –