An example of using session across domains in webapi

Time:2019-10-28

In previous projects, we set cross domain settings directly in web.config.

This enables cross domain access. Because we usually have multiple websites, applets, wechat public accounts and so on for a webapi, there is no problem with this setting. But… If one of the websites needs to use cookies or sessions,

If access control allow origin is still set to “*”, an error will be reported. Of course, it is the front-end error. Data return and Cookie / session can still be saved, but it’s not good to report an error.

So, I want to rectify it.

Start with the front-end code. Send a page remote Ajax request to set the session. Nothing. Just click the button and send a request. It is necessary to mark the place

@{
  ViewBag.Title = "TestSetSession";
}

<h2>TestSetSession</h2>

< button onclick = "set()" > set 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)
        },
        error: function () {
          Alert ('server error! ).
        }
      });
    }
  </script>
}

Then another page to get the session set by the previous page.

@{
  ViewBag.Title = "TestGetSession";
}

<h2>TestGetSession</h2>
< button onclick = "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 ('server error! ).
        }
      });
    }
  </script>
}

Background code

1. Allow webapi to use session first

Add the following code to global


public override void Init()
    {
      PostAuthenticateRequest += 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 use microsoft.aspnet.webapi.cors here

Install the package first, and then add the following code to webapiconfig. Equivalent to setting in web.config

//Allow cross domain
  config.EnableCors(new EnableCorsAttribute("*", "*", "*"));

Label [enablecors] on the request method, which means that cookies / sessions are required for access to some domain names.

[EnableCors("http://localhost:6477,http://localhost:6478", "*","*")]
  public class TestController : ApiController
  {
    /// <summary>
    ///Set session
    /// </summary>
    /// <returns></returns>
    public dynamic SetSession(string session)
    {
      HttpContext.Current.Response.AddHeader("Access-Control-Allow-Credentials", "true");
      //Cache state
      HttpContext.Current.Session["session_test"] = session;
      HttpCookie cookie = new HttpCookie("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 dynamic GetSession()
    {
      HttpContext.Current.Response.AddHeader("Access-Control-Allow-Credentials", "true");
      var session = HttpContext.Current.Session["session_test"];
      HttpCookie _cookie = HttpContext.Current.Request.Cookies["cookie_test"];
      var cookie = _cookie?.Value??"";
      string session_state = session == null ? "" : session.ToString();
      return new 
      {
        success = true,
        Message = "get session",
        data = new { session_state, cookie }
      };
    }

Result:

The above is the whole content of this article. I hope it will help you in your study, and I hope you can support developepaer more.