In the previous project, we set the cross-domain to be set directly in Web. config.
This enables cross-domain access. Because we usually have a webapi there will be multiple sites, small programs, public numbers and other access, so this setting is not a problem. But...... If one of the sites needs a cookie or a session,
Access-control-allow-origin if still set to "*" will be an error, of course, the front end error ... Data return and Cookie/session are still able to save, but the error is uncomfortable ah.
So, think about the rectification.
First, the front-end code. A page to the remote AJAX request to set the session. Nothing, just a button, send a request. Mark the place to be added
@{Viewbag.title="testsetsession";}"Set ()"> Setup session</button>@section scripts{<script src="~/scripts/jquery-1.10.2.min.js"></script> <script>function Set () {$.ajax ({URL:"Http://localhost:1338/api/Test/SetSession?session=1234567fdsdfghjhgfds", DataType:"JSON", xhrfields: {withcredentials: true }, Crossdomain: true , data: {}, type:"Post", Success:function (data) {alert (data.message)}, er Ror:function () {alert ('The server has an error! '); } }); } </script>}
And then a page to get the last page Setup session.
@{Viewbag.title="testgetsession";}"Get ()"> Get session</button>@section scripts{<script src="~/scripts/jquery-1.10.2.min.js"></script> <script>function Get () {$.ajax ({URL:"http://localhost:1338/api/Test/GetSession", DataType:"JSON", xhrfields: {withcredentials: true }, Crossdomain: true , data: {}, type:"Get", Success:function (data) {alert ("session:" + data.data.session_state + ", Cookie:" + Data.data.cookie); }, Error:function () {alert ('The server has an error! '); } }); } </script>}
Background code
1. Allow Webapi to use session first
Add the following code to global
Public Override void Init () { + = mvcapplication_postauthenticaterequest ; Base . Init (); } void Mvcapplication_postauthenticaterequest (object sender, EventArgs e) { System.Web.HttpContext.Current.SetSessionStateBehavior ( System.Web.SessionState.SessionStateBehavior.Required); }
2. Allow cross-domain. I'm using Microsoft.AspNet.WebApi.Cors here.
Install the package first, and then add the following code to the Webapiconfig. Equivalent to setting in Web. config
// allow cross-domain Config. Enablecors (new Enablecorsattribute ("*""* " "*"));
On the request method to hit the [Enablecors] label, specifically for some domain name access needs cookie/session
[Enablecors ("http://localhost:6477,http://localhost:6478","*","*")] Public classTestcontroller:apicontroller {/// <summary> ///Set Session/// </summary> /// <returns></returns> Public DynamicSetsession (stringsession) {HttpContext.Current.Response.AddHeader ("access-control-allow-credentials","true"); //Cache Statehttpcontext.current.session["session_test"] =session; HttpCookie Cookies=NewHttpCookie ("cookie_test") {Value=session, Expires= DateTime.Now.AddHours (1) }; HTTPCONTEXT.CURRENT.RESPONSE.COOKIES.ADD (cookie); return New{Success=true, Message="Set Session" }; } /// <summary> ///Get Session/// </summary> /// <returns></returns> Public Dynamicgetsession () {HttpContext.Current.Response.AddHeader ("access-control-allow-credentials","true"); varSession = httpcontext.current.session["session_test"]; HttpCookie _cookie= httpcontext.current.request.cookies["cookie_test"]; varCookie = _cookie?. Value??""; stringSession_state = Session = =NULL?"": Session. ToString (); return New{Success=true, Message="Get Session", the data=New{session_state, Cookie}}; }
Results:
WEBAPI cross-Domain use session