簡體   English   中英

對預檢請求的響應未通過訪問控制檢查(Angular2)

[英]Response to preflight request doesn't pass access control check (Angular2)

我在Asp.net中調用REST Web API時遇到錯誤。

XMLHttpRequest無法加載http:// localhost:54859 / api / PostData 對預檢請求的響應未通過訪問控制檢查:請求的資源上不存在“Access-Control-Allow-Origin”標頭。 因此不允許來源' http:// localhost:3000 '訪問。

我使用Angular2作為前端。 在后端,我添加了以下代碼以在WEB API中啟用CORS。

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

一切都適用於Http get請求,但同樣不適用於Http Post請求。

任何幫助都會很明顯

提前致謝!

我通過在web.config中添加以下行來解決它。

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

謝謝。

在Global.asax.cs中的Application_BeginRequest期間為預檢請求添加Access-Control-Allow-Origin標頭為我工作。

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

解決此問題后,應用程序在瀏覽器控制台上拋出了錯誤,即在預檢響應中未提及某些標頭。

將標題添加到預檢響應的Access-Control-Allow-Headers標頭后,它就會得到解決。

protected void Application_BeginRequest(Object sender, EventArgs e)
{
    // Preflight request comes with HttpMethod OPTIONS
        // The following line solves the error message
        HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
    if (HttpContext.Current.Request.HttpMethod == "OPTIONS")            
    {
        HttpContext.Current.Response.AddHeader("Cache-Control", "no-cache");
        HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST");               
        // 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();
    }
}

上面的代碼運行正常

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM