当前位置:首页 > Windows程序 > 正文

Asp.net Vnext api CORS( 跨域)

2021-03-29 Windows程序

跨域资源共享(CORS )是一种网络浏览器的技术规范,它为Web服务器定义了一种方式,允许网页从不同的域访问其资源。而这种访问是被同源策略所禁止的。CORS系统定义了一种浏览器和服务器交互的方式来确定是否允许跨域请求。 它是一个妥协,有更大的灵活性,,但比起简单地允许所有这些的要求来说更加安全。

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(":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=http://www.mamicode.com/"viewport" content=http://www.mamicode.com/"width=device-width" /> <title>Index</title> <script src=http://www.mamicode.com/"~/Scripts/jquery-1.10.2.js"></script> <script type=http://www.mamicode.com/"text/javascript"></script> </head> <body> <div> <input type=http://www.mamicode.com/"button" id=http://www.mamicode.com/"cros" value=http://www.mamicode.com/"获取跨域" /> <div id=http://www.mamicode.com/"msg"></div> </div> <script type=http://www.mamicode.com/"text/javascript"> $(function () { $("#cros").click(function () { $.ajax({ url: ":49271/Cors/GetBlogComments", type: "POST", success: function (d) { $("#msg").html(d) } }) }); }); </script> </body> </html>

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

修改一视图,支持跨域Cookie

温馨提示: 本文由Jm博客推荐,转载请保留链接: https://www.jmwww.net/file/69927.html