简体   繁体   中英

origin 'http://localhost:4200' has been blocked by CORS policy

Have an application in angular 7 also has an .net web api solution , when i call an action CORS issue occurs , error follows

Access to XMLHttpRequest at ' http://localhost:57467/UserDetails/GetUserDetails ' from origin ' http://localhost:4200 ' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

I tried to add CORS fix using using System.Web.Http.Cors in web api but still error occurs .Thanks in advance .Help me out of this problem

     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 call from angular

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

I think the if clause within the Application_BeginRequest method is preventing the 'Access-Control-Allow-Origin' header to be added to the response.

you should try without the if clause by simply adding the allowedOrigin value to Access-Control-Allow-Origin . So, the Application_BeginRequest() would look something like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM