【问题标题】:origin 'http://localhost:4200' has been blocked by CORS policy来源 'http://localhost:4200' 已被 CORS 策略阻止
【发布时间】: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


    【解决方案1】:

    我认为Application_BeginRequest 方法中的if 子句会阻止将“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");
    }
    

    【讨论】:

      猜你喜欢
      • 2020-01-26
      • 2019-10-13
      • 2019-10-31
      • 2020-07-09
      • 2019-11-16
      • 1970-01-01
      • 2019-11-17
      • 2020-10-12
      • 1970-01-01
      相关资源
      最近更新 更多