2016-11-11 1 views
2

Ich bekomme unter Fehler beim Aufruf der REST-Web-API in Asp.net.Antwort auf Preflight-Anfrage nicht passieren Kontrolle der Zugriffskontrolle (Angular2)

XMLHttpRequest kann http://localhost:54859/api/PostData nicht geladen werden. Die Antwort auf die Preflight-Anforderung übergibt die Zugriffskontrollprüfung nicht: Auf der angeforderten Ressource ist kein Header "Access-Control-Allow-Origin" vorhanden. Origin 'http://localhost:3000' ist daher nicht erlaubt.

Ich benutze Angular2 als Frontend. Im Backend habe ich folgende Codes hinzugefügt, um CORS in der WEB API zu aktivieren.

var corsAttr = new EnableCorsAttribute("*", "*", "*"); 
config.EnableCors(corsAttr); 

Alles funktioniert gut für Http Anfrage erhalten, aber das gleiche nicht für Http Post Anfrage.

Jede Hilfe wäre

Vielen Dank im Voraus spürbar sein!

Antwort

2

Ich habe es durch Hinzufügen von folgenden Zeilen zu web.config gelöst.

<system.webServer> 
    <modules runAllManagedModulesForAllRequests="true"> 
    </modules> 
</system.webServer> 

Danke.

3

Hinzufügen von Access-Control-Allow-Origin Header für die Preflight-Anfrage während Application_BeginRequest in Global.asax.cs arbeitete für mich.

Global.asax/Global.asax.cs

protected void Application_BeginRequest(Object sender, EventArgs e) 
    { 
     // Preflight request comes with HttpMethod OPTIONS 
     if (HttpContext.Current.Request.HttpMethod == "OPTIONS")    
     { 
      HttpContext.Current.Response.AddHeader("Cache-Control", "no-cache"); 
      HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST");    
      // The following line solves the error message 
      HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*"); 
      // If any http headers are shown in preflight error in browser console add them below 
      HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept, Pragma, Cache-Control, Authorization "); 
      HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000"); 
      HttpContext.Current.Response.End(); 
     } 
    } 

Nach diesem Problem zu lösen, warfen die Anwendungsfehler auf Browser-Konsole, die bestimmten Header werden nicht in Preflight Antwort erwähnt.

Sobald die Header zu Access-Control-Allow-Headers Header der Preflight-Antwort hinzugefügt wurden, wurde es aufgelöst.

Verwandte Themen