溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

怎么在webapi中使用session實現(xiàn)跨域

發(fā)布時間:2021-03-26 16:54:35 來源:億速云 閱讀:272 作者:Leah 欄目:開發(fā)技術

這篇文章給大家介紹怎么在webapi中使用session實現(xiàn)跨域,內容非常詳細,感興趣的小伙伴們可以參考借鑒,希望對大家能有所幫助。

在之前的項目中,我們設置跨域都是直接在web.config中設置的。

怎么在webapi中使用session實現(xiàn)跨域

這樣是可以實現(xiàn)跨域訪問的。因為我們這邊一般情況下一個webapi會有多個網站、小程序、微信公眾號等訪問,所以這樣設置是沒有問題的。但是……如果其中一個網站需要用到cookie或者session的時候,

Access-Control-Allow-Origin如果還是設置成“*”就會報錯,當然是前端報錯。。。數(shù)據(jù)返回還有cookie/session都還是能存,但是報錯就不爽了啊。

于是,想著整改一下。

先上前端代碼。來個頁面遠程ajax請求去設置session。啥都沒有,就是點按鈕,發(fā)個請求。標記地方是必須加的

@{
  ViewBag.Title = "TestSetSession";
}

<h3>TestSetSession</h3>

<button onclick="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('服務器發(fā)生錯誤!');
        }
      });
    }
  </script>
}

然后再來個頁面,獲取上個頁面設置的session。

@{
  ViewBag.Title = "TestGetSession";
}

<h3>TestGetSession</h3>
<button onclick="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('服務器發(fā)生錯誤!');
        }
      });
    }
  </script>
}

后臺代碼

1.先允許webapi使用session

在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.允許跨域。我這里使用的是Microsoft.AspNet.WebApi.Cors

先安裝包,然后在WebApiConfig中加入如下代碼。等同于在web.config中設置

 //允許跨域
  config.EnableCors(new EnableCorsAttribute("*", "*", "*"));

在請求方法上打上[EnableCors]標簽,特指某一些域名的訪問需要cookie/session

[EnableCors("http://localhost:6477,http://localhost:6478", "*","*")]
  public class TestController : ApiController
  {
    /// <summary>
    /// 設置session
    /// </summary>
    /// <returns></returns>
    public dynamic SetSession(string session)
    {
      HttpContext.Current.Response.AddHeader("Access-Control-Allow-Credentials", "true");
      //緩存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 = "設置session"
      };
    }

    /// <summary>
    /// 獲取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 = "獲取session",
        data = new { session_state, cookie }
      };
    }

結果:

怎么在webapi中使用session實現(xiàn)跨域

怎么在webapi中使用session實現(xiàn)跨域

關于怎么在webapi中使用session實現(xiàn)跨域就分享到這里了,希望以上內容可以對大家有一定的幫助,可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經查實,將立刻刪除涉嫌侵權內容。

AI