[英]Angular 4 / Asp.net Web API - No 'Access-Control-Allow-Origin' header is present
I'm trying to call the API from angular and getting this errors. 我试图从角度调用API,并得到此错误。 I donot want to set proxy in angular instead allow CORS in Angular 4 and Web API.
我不想在angular中设置代理,而是在Angular 4和Web API中允许CORS。
Following is my code: 以下是我的代码:
let reHeader: RequestOptions = new RequestOptions();
reHeader.headers = new Headers();
reHeader.headers.append("content-type", "application/json");
reHeader.headers.append("x-api-key", store.APIKey);
reHeader.headers.append('Access-Control-Allow-Origin','*');
reHeader.headers.append('Access-Control-Allow-Methods', "GET, POST, PATCH, PUT, DELETE, OPTIONS")
reHeader.headers.append('Access-Control-Allow-Headers', "Origin, Content-Type, X-Auth-Token")
switch (rtype) {
case "get":
let query: string = "";
action.ActionParams.forEach(m => {
query += "&" + m.Key + "=" + m.Value;
});
url = url + query;
return this.http.get(url, reHeader);
default:
return Observable.of(null);
}
and from WEB API in startup.cs 并从startup.cs中的WEB API
public void Configuration(IAppBuilder app)
{
app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
// ASPNETCORE_ENVIRONMENT should be set to 'Development'
if (env != null && env.IsDevelopment())
{
app.UseErrorPage(ErrorPageOptions.ShowAll);
}
var config = new HttpConfiguration();
ConfigureWebApi(config);
// Swagger
SwaggerConfig.Register(config);
// Register routes
WebApiConfig.Register(config);
}
I have checked other posts but still didnt get solution. 我检查了其他帖子,但仍未获得解决方案。 - Angular 2 Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header
-Angular 2对预检请求的响应未通过访问控制检查:没有“ Access-Control-Allow-Origin”标头
Add below code in Global.asax and try 在Global.asax中添加以下代码,然后尝试
protected void Application_BeginRequest(Object sender, EventArgs e)
{
if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
{
HttpContext.Current.Response.AddHeader("Cache-Control", "no-cache");
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST");
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept, Pragma, Cache-Control, Authorization ");
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
HttpContext.Current.Response.End();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.