【发布时间】:2019-12-29 14:36:38
【问题描述】:
在 Angular 7 中有一个应用程序也有一个 .net web api 解决方案,当我调用一个动作 CORS 问题时,错误如下
从源“http://localhost:4200”对“http://localhost:57467/UserDetails/GetUserDetails”处的 XMLHttpRequest 的访问已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:没有“Access-Control-Allow-Origin”标头出现在请求的资源上。
我尝试在 web api 中使用 System.Web.Http.Cors 添加 CORS 修复,但仍然出现错误。在此先感谢。帮我解决这个问题
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
EnableCorsAttribute cors = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(cors);
// Web API configuration and services http://localhost:80/DemoApp/WebForm1.aspx
// Configure Web API to use only bearer token authentication.
config.SuppressDefaultHostAuthentication();
config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
global.asax.cs
protected void Application_BeginRequest()
{
string[] allowedOrigin = new string[] { "http://localhost:4200", "http://localhost:2052" };
var origin = HttpContext.Current.Request.Headers["Origin"];
if (origin != null && allowedOrigin.Contains(origin))
{
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", origin);
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET,POST");
}
}
从角度调用 api
let headers = new HttpHeaders({ 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*' });
let options = { headers: headers, crossDomain: true, withCredentials: true };
return this._http.get(path, options)
.pipe(map(res => {
return JSON.parse(res.toString());
}),
catchError(this.handleError)
);
【问题讨论】:
标签: javascript c# asp.net-web-api cors angular7