我很努力地理解和啓用一個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分鐘)。 –