当前位置: 首页 > 知识库问答 >
问题:

起源'http://localhost:4200'已被CORS策略阻止

葛航
2023-03-14

有一个应用程序在角7也有一个. net web api解决方案,当我调用一个动作CORS问题发生,错误如下

CORS策略阻止从http://localhost:57467/UserDetails/GetUserDetailshttp://localhost:4200访问XMLHttpRequest:对预试请求的响应不通过权限改造检查:请求的资源上不存在访问控制允许起源标头。

我试图使用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");
        }
    }

来自angular的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)
        );

共有1个答案

陈哲
2023-03-14

我认为Application\u BeginRequest方法中的if子句阻止将“Access Control Allow Origin”头添加到响应中。

您应该尝试不使用if子句,只需将allowedOrigin值添加到Access Control Allow Origin。因此,应用程序\u 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");
}
 类似资料: