Asp.net Vnext api CORS( 跨域)


 

概述


 

跨域資源共享(CORS )是一種網絡瀏覽器的技術規范,它為Web服務器定義了一種方式,允許網頁從不同的域訪問其資源。而這種訪問是被同源策略所禁止的。CORS系統定義了一種瀏覽器和服務器交互的方式來確定是否允許跨域請求。 它是一個妥協,有更大的靈活性,但比起簡單地允許所有這些的要求來說更加安全。 本文已經同步到《Asp.net Vnext 系列教程 》中]

CORS通過設置HTTP Header(標頭)設置網站跨域存取。

 

Access-Control-Allow-Origin 允許跨域訪問的域,可以是一個域的列表,也可以是通配符"*"。
Access-Control-Allow-Credentials 默認情況下,跨源請求不提供憑據(cookie、HTTP認證及客戶端SSL證明等)。通過將withCredentials屬性設置為true,可以指定某個請求應該發送憑據。如果服務器接收帶憑據的請求,會用下面的HTTP頭部來響應
Access-Control-Expose-Headers 需要客戶端公開標頭。
Access-Control-Allow-Methods 允許使用的請求方法,以逗號隔開
Access-Control-Allow-Headers  允許自定義的頭部,以逗號隔開,大小寫不敏感

實例代碼


 

啟動類

     public void ConfigureServices(IServiceCollection services)
            {
            services.AddMvc();
            services.ConfigureCors(options =>
            {
                options.AddPolicy(
                    "AllowAnySimpleRequest",
                    builder =>
                    {
                        //允許全部訪問域
                        builder.AllowAnyOrigin()
                            //允許全部請求方法  //允許全部標頭  //允許全部憑據
                            .AllowAnyMethod().AllowAnyHeader().AllowCredentials();
                    });

                options.AddPolicy(
                    "AllowSpecificOrigin",
                    builder =>
                    {
                        builder.AllowCredentials().WithOrigins("http://localhost:57096/")
                        //只允許 post  
                        .WithMethods("POST")
                          .AllowAnyHeader()
                          //公開的標頭
                      . WithExposedHeaders("exposed11", "exposed22");


                    });

            });
            }

控制器

  [Route("Cors/[action]")]
    [EnableCors("AllowAnySimpleRequest")]
    public class BlogController : Controller
    {
        [EnableCors("AllowSpecificOrigin")]
        public IEnumerable<string> GetBlogComments(int id)
        {
            return new[] { "comment1", "comment2", "comment3" };
        }

1.新建一個Mvc程序

2.控制器

 public class HomeController : Controller
    {
        // GET: Home
        public ActionResult Index()
        {
            //加入Cookie
            Response.Cookies.Add(new HttpCookie("111") { Value = "2222", Expires = DateTime.Now.AddDays(2) });

            return View();
        }
    }

視圖

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
    <script src="~/Scripts/jquery-1.10.2.js"></script>
   <script type="text/javascript"></script>
</head>
<body>
    <div>
        <input type="button" id="cros" value="獲取跨域" />
        <div id="msg"></div>
    </div>
    <script type="text/javascript">
        $(function () {
            $("#cros").click(function () {
                $.ajax({
                  
                    url: "http://localhost:49271/Cors/GetBlogComments",
                    type: "POST",
                    success: function (d) {
                        $("#msg").html(d)
                    }
                })

            });
        });
    </script>
</body>

</html>

 

已經加入要公開的標頭了。

修改一視圖,支持跨域Cookie

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
    <script src="~/Scripts/jquery-1.10.2.js"></script>
   <script type="text/javascript">
       window.onload = function ()
       {
           alert("11");
           var xhr = new XMLHttpRequest(); 
           xhr.open("get", "http://localhost:49271/Cors/GetBlogComments", true);
            xhr.withCredentials = true; //支持跨域發送cookies 
           xhr.send();
       }
   </script>
</head>
<body>
    <div>
        <input type="button" id="cros" value="獲取跨域" />
        <div id="msg"></div>
    </div>
    <script type="text/javascript">
        $(function () {
            $("#cros").click(function () {
                $.ajax({
                  
                    url: "http://localhost:49271/Cors/GetBlogComments",
                    type: "POST",
                    success: function (d) {
                        $("#msg").html(d)
                    }
                })

            });
        });
    </script>
</body>

</html>

 

已經獲得Cookie。

 

                                                               得到你的肯定是我最大的動力。


免責聲明!

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



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