Asp.net Vnext api CORS( 跨域) 概述                                                                得到你的肯定是我最大的动力。

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>

Asp.net Vnext  api  CORS( 跨域)
概述
                                                               得到你的肯定是我最大的动力。

已经加入要公开的标头了。

修改一视图,支持跨域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>

Asp.net Vnext  api  CORS( 跨域)
概述
                                                               得到你的肯定是我最大的动力。

已经获得Cookie。

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