WEBAPI cross-Domain use session

Source: Internet
Author: User
Tags httpcontext

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}}; }


WEBAPI cross-Domain use session

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.