原点“ http:// localhost:4200”已被CORS策略阻止

时间:2019-08-24 17:57:00

标签: javascript c# asp.net-web-api cors angular7

在angular 7中有一个应用程序也有一个.net Web api解决方案,当我调用操作发生CORS问题时,就会出现错误

从原点“ http://localhost:57467/UserDetails/GetUserDetails”到“ http://localhost:4200”处对XMLHttpRequest的访问已被CORS策略阻止:对预检请求的响应未通过访问控制检查:否'Access-Control-Allow-来源的标头出现在请求的资源上。

我尝试在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");
        }
    }

角度调用

    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)
        );

1 个答案:

答案 0 :(得分:0)

我认为if方法中的Application_BeginRequest子句阻止将'Access-Control-Allow-Origin'标头添加到响应中。

您应该通过简单地将if值添加到allowedOrigin来尝试不使用Access-Control-Allow-Origin子句。因此,Application_BeginRequest()看起来像这样:

protected void Application_BeginRequest()
{
    string[] allowedOrigin = new string[] { "http://localhost:4200", "http://localhost:2052" };
    HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", allowedOrigin);
    HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET,POST");
}