欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

webapi跨域使用session的方法示例

 更新時(shí)間:2018年07月30日 15:19:31   作者:zhaoshang  
這篇文章主要介紹了webapi跨域使用session的方法示例,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧

在之前的項(xiàng)目中,我們?cè)O(shè)置跨域都是直接在web.config中設(shè)置的。

這樣是可以實(shí)現(xiàn)跨域訪問的。因?yàn)槲覀冞@邊一般情況下一個(gè)webapi會(huì)有多個(gè)網(wǎng)站、小程序、微信公眾號(hào)等訪問,所以這樣設(shè)置是沒有問題的。但是……如果其中一個(gè)網(wǎng)站需要用到cookie或者session的時(shí)候,

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

于是,想著整改一下。

先上前端代碼。來個(gè)頁面遠(yuǎn)程ajax請(qǐng)求去設(shè)置session。啥都沒有,就是點(diǎn)按鈕,發(fā)個(gè)請(qǐng)求。標(biāo)記地方是必須加的

@{
  ViewBag.Title = "TestSetSession";
}

<h2>TestSetSession</h2>

<button onclick="Set()">設(shè)置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('服務(wù)器發(fā)生錯(cuò)誤!');
        }
      });
    }
  </script>
}

然后再來個(gè)頁面,獲取上個(gè)頁面設(shè)置的session。

@{
  ViewBag.Title = "TestGetSession";
}

<h2>TestGetSession</h2>
<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('服務(wù)器發(fā)生錯(cuò)誤!');
        }
      });
    }
  </script>
}

后臺(tái)代碼

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中設(shè)置

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

在請(qǐng)求方法上打上[EnableCors]標(biāo)簽,特指某一些域名的訪問需要cookie/session

[EnableCors("http://localhost:6477,http://localhost:6478", "*","*")]
  public class TestController : ApiController
  {
    /// <summary>
    /// 設(shè)置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 = "設(shè)置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 }
      };
    }

結(jié)果:

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

您可能感興趣的文章:

相關(guān)文章

最新評(píng)論