跨域需要服务端和客户端都作处理。

首先让asp.net core跨域,在nuget中添加Microsoft.AspNetCore.Cors的引用,然后在StartUp.cs中的ConfigureServices中添加如下代码:

varurls="http://localhost:5000/";services.AddCors(options=>options.AddPolicy("MyDomain",builder=>builder.WithOrigins(urls).AllowAnyMethod().AllowAnyHeader().AllowAnyOrigin().AllowCredentials()));

再在Configure中添加

app.UseCors("AllowSameDomain");

再添加验证,添加Microsoft.AspNetCore.Authentication.Cookies引用在Configure中添加

app.UseCookieAuthentication(newCookieAuthenticationOptions{AuthenticationScheme="validates",LoginPath=newMicrosoft.AspNetCore.Http.PathString("/login"),AccessDeniedPath=newMicrosoft.AspNetCore.Http.PathString("/Home/Error"),AutomaticAuthenticate=true,AutomaticChallenge=true,SlidingExpiration=true});

在Controller中添加允许跨域特性,然后再添验证特性

usingMicrosoft.AspNetCore.Mvc;usingMicrosoft.AspNetCore.Cors;usingMicrosoft.AspNetCore.Authorization;usingSystem.Security.Claims;namespaceWebUI.Controllers{[Authorize(Roles="Admin")][EnableCors("MyDomain")]publicclassHomeController:Controller{///<summary>///测试方法///</summary>///<paramname="item"></param>///<returns></returns>[HttpPost("additem")]publicIActionResultAddItem(Itemitem){returnnewJsonResult(new{Result=0,Message="添加成功",Content=item.ToString(),UserName=User.Identity.Name},newNewtonsoft.Json.JsonSerializerSettings());}///<summary>///登录///</summary>///<paramname="username">用户名</param>///<paramname="password">密码</param>///<returns></returns>[AllowAnonymous][HttpPost("login")]publicIActionResultLogin(stringusername,stringpassword){if(username=="aaa"&&password=="111"){varuser=new{RoleType=1,Name="张三丰",ID=1};stringroleId=user.RoleType.ToString();varroleName="";switch(roleId){case"1":roleName="Admin";//管理员break;}varid=user.ID.ToString();varclaims=newClaim[]{newClaim(ClaimTypes.UserData,roleId),newClaim(ClaimTypes.Role,roleName),newClaim(ClaimTypes.Name,username)};HttpContext.Authentication.SignInAsync("validates",newClaimsPrincipal(newClaimsIdentity(claims,"Cookie")));HttpContext.User=newClaimsPrincipal(newClaimsIdentity(claims));returnnewJsonResult(new{Message="登录成功"},newNewtonsoft.Json.JsonSerializerSettings());}else{returnnewJsonResult(new{Message="用户名或密码错误"},newNewtonsoft.Json.JsonSerializerSettings());}}}}

在JQuery中,使用$.ajax登录后,才能执行保存,否则没有权限保存数据,重点时ajax请求时xhrFields:{withCredentials:true}这个属性,可以把登录后的cookie在后面的操作中带回服务端(关于原理不多说了)

<!DOCTYPEhtml><html><head><metahttp-equiv="Content-Type"content="text/html;charset=utf-8"/><title></title><metacharset="utf-8"/><scriptsrc="bower_components/jquery/dist/jquery.js"></script></head><body><inputid="login"value="登录"type="button"/><inputid="sava"value="保存"type="button"/><spanid="message"></span><script>$("#login").click(function(){$.ajax({type:'POST',url:"http://localhost:5000/login",data:{username:"aaa",password:"111"},dataType:"json",xhrFields:{withCredentials:true},success:function(result){$("#message").html(result.Message);},error:function(){$("#message").html("登录失败!");}});})$("#sava").click(function(){$.ajax({type:'POST',url:"http://localhost:5000/additem",data:{ID:112,Name:"李四",Birthday:"2017-01-23"},dataType:"json",//必须有这项的配置,不然cookie无法发送至服务端xhrFields:{withCredentials:true},success:function(result){$("#message").html(result.Message+result.Content+result.UserName);},error:function(xhr,status){$("#message").html(status);}});})</script></body></html>

来看一下测试结果:

当直接点保存时,系统会导航登录


登录


再次保存