.net core的允許跨域訪問三個問題解決


一,我們看看什么是跨域
我們可以理解頁面發起當一個請求 url 的協議、域名、端口三者之間任意一個與當前頁面 url 不同即為跨域。那為什么會出現跨域問題呢?

 

二,我們先理解跨域的結果是怎樣的

如下圖結果:

 

 而瀏覽器提示錯誤,如下圖

 由上圖我們可以得出結論,其實服務器是返回成功的200,跨域的結果其實是瀏覽器限制了你的請求

 

三,那為什么瀏覽器會限制呢?

由於瀏覽器的同源策略限制,同源策略(Sameoriginpolicy)是一種約定,它是瀏覽器最核心也最基本的安全功能,如果缺少了同源策略,則瀏覽器的正常功能可能都會受到影響。
可以說 Web 是構建在同源策略基礎之上的,瀏覽器只是針對同源策略的一種實現。同源策略會阻止一個域的 javascript 腳本和另外一個域的內容進行交互。所謂同源(即指在同一個域)就是兩個頁面具有相同的協議(protocol),主機(host)和端口號(port)

 

四,那在.net core我們怎么解決跨域問題呢,這個時候我們的cors就出場了,我們看下微軟官方文檔看下cors的解釋

 

五,看下我們的代碼實現三種類型
1》跨源(cross-origin)不帶請求證書(Credentials)

 js方法如下

      $("#btn1").click(function () {
            //alert(11);
            $.ajax({
                url: 'http://localhost:8000/Home/Get',
                type: 'Get',
                success: function (res) {
                    alert(res.name);
                }
            });
        })

請求結果如下

 這個*號是AllowAnyOrigin,設置返回的,返回是允許所有源的意思,如下代碼

            #region 普通的跨域驗證,不帶請求中的證書

            app.UseCors(builder =>
            {
                builder.AllowAnyOrigin()
                       .AllowAnyHeader()
                       .AllowAnyMethod()
                       .SetPreflightMaxAge(TimeSpan.FromSeconds(2000000));
            });
            #endregion

 
2》跨源(cross-origin)帶請求證書(Credentials)

 

        $("#btn2").click(function () {
            //alert(11);
            $.ajax({
                url: 'http://localhost:8000/Home/Get',
                type: 'Get',
                xhrFields: { withCredentials: true },
                crossDomain: true,
                success: function (res) {
                    alert(res.name);
                }
            });
        })

 

我們使用第二種請求方式,而這個時候如果我們開啟了,卻沒有改后端配值,我們發起請求發現。回報如下跨域:Access to XMLHttpRequest at 'http://localhost:8000/Home/Get' from origin 'http://localhost:5000' has been blocked by CORS policy: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.

這個是什么原因導致的呢?我們看看ajax請求,因為我們使用了 withCredentials: true,而恰恰這個使用是不允許AllowAnyOrigin()的,意思就是不允許返回的Access-Control-Allow-Origin:*,那我們的處理方式如下

我們看看的配置,如下代碼,我們必須開啟AllowCredentials,同時去掉AllowAnyOrigin,這兩個

            #region 跨源(cross-origin)請求中的證書(Credentials) 不帶自定義參數
            ////當在ajax設置了withCredentials: true,就是要帶域名的cookie,同時這里是不允許返回Access - Control - Allow - Origin: *這個帶星號的,這個時候,我們就要設置允許的參數了

            app.UseCors(builder =>
            {
                builder.SetIsOriginAllowed(_ => true)
               .AllowCredentials();
            });

            #endregion

 這個時候我們看看請求結果到底有什么區別,如下圖

 發現我們的請求head多了了Access-Control-Allow-Credentials:true和帶了cookie

 

3》跨源(cross-origin)帶請求證書(Credentials)+自定義head參數

如果我們在請求頭加自定義參數,我們這個時候又會提示跨域,如下js方法如下

   $("#btn3").click(function () {
            //alert(11);
            $.ajax({
                url: 'http://localhost:8000/Home/Get',
                type: 'Get',
                headers: {
                    'content-type': 'application/json;charset=UTF-8',
                    'test': "123",
                    'authorization': '456'
                },
                xhrFields: { withCredentials: true },
                crossDomain: true,
                success: function (res) {
                    alert(res.name);
                }
            });
        })

 如下圖錯誤:Access to XMLHttpRequest at 'http://localhost:8000/Home/Get' from origin 'http://localhost:5000' has been blocked by CORS policy: Request header field test is not allowed by Access-Control-Allow-Headers in preflight response.

 

 這是為什么呢?這個是時候就是我們必須在后端代碼配置請求頭參數,如下代碼

   #region    #region 跨源(cross-origin)請求中的證書(Credentials)+ 帶自定義參數
            ////當在ajax設置了withCredentials: true,就是要帶域名的cookie,同時這里是不允許返回Access - Control - Allow - Origin: *這個帶星號的,這個時候,我們就要設置允許的參數了
            app.UseCors(builder =>
            {
                builder.WithHeaders("authorization", "test", "content-type") //如果開啟帶檢驗,並且ajax的headers頭部自帶自定義參數時。必須帶上自定義的
                       .SetIsOriginAllowed(_ => true)
                      .AllowCredentials();
            });
            #endregion

這個時候我們看看請求的請求頭,如下

我們也要在后端添加上如下幾個接受,才是不提示跨域的問題 !!!

 當然,如果不想設置參數,我們可以允許所有的頭

            app.UseCors(builder =>
            {
                builder.SetIsOriginAllowed(_ => true)
                      .AllowCredentials()
                      .AllowAnyHeader();
            });

為了安全我們可以設置固定的域名,來源

            app.UseCors(builder =>
            {
                builder.WithOrigins("http://localhost:5000")
                      .AllowCredentials()
                      .AllowAnyHeader();
            });

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM