1、Global.asax中添加對Session的支持,重新Init方法: 2、WebConfig中添加跨域支持: 3、寫Session的Controller 4、讀Session的Controller 5、前端jQuery調用時加上參數crossDomain: true 和 xhrFields: ...
1、Global.asax中添加對Session的支持,重新Init方法:
public override void Init() { this.PostAuthenticateRequest += (sender, e) => HttpContext.Current.SetSessionStateBehavior (System.Web.SessionState.SessionStateBehavior.Required); base.Init(); }
2、WebConfig中添加跨域支持:
<httpProtocol> <customHeaders> <clear /> <add name="Access-Control-Allow-Origin" value="http://*.*.*.*:8088" /> <add name="Access-Control-Allow-Credentials" value="true" /> <add name="Access-Control-Allow-Headers" value="Content-Type" /> <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" /> </customHeaders> </httpProtocol>
3、寫Session的Controller
[RoutePrefix("Reg")] public class RegController : ApiController { [Route("RegUser")] [HttpGet] public bool RegUser(string userName) { System.Web.HttpContext.Current.Session["User"] = userName; return true; } }
4、讀Session的Controller
[RoutePrefix("Login")] public class LoginController : ApiController { [Route("GetLogin")] [HttpGet] public string GetLogin() { string userName = string.Empty; if(System.Web.HttpContext.Current.Session["User"]!=null) { userName = System.Web.HttpContext.Current.Session["User"].ToString(); } return userName; } }
5、前端jQuery調用時加上參數crossDomain: true 和 xhrFields: { withCredentials: true}。
<script> var url = "http://*.*.*.*:8089/"; var userId = "002"; var userName = "xiaoming"; var password = "123456"; $(function () { btnRegClick(); btnGetNameClick(); }); function btnRegClick(){ $("#btnReg").click(function () { $.ajax({ type: "get", url: url + "Reg/RegUser", xhrFields: { withCredentials: true }, crossDomain: true, data: { userId: userId, userName: userName, password: password }, success: function (result) { $("#txtUserName").val(result) } }); }); } function btnGetNameClick(){ $("#btnGetName").click(function () { $.ajax({ type: "get", url: url + "Login/GetLogin", xhrFields: { withCredentials: true }, crossDomain: true, data: { }, success: function (result) { $("#txtUserName").val(result) } }); }); } <script>
6、搞定。