首页 > 解决方案 > 如何在 Web API 控制器中读取 ASP.NET_SessionId?

问题描述

我们有一个遗留的 ASP.NET WebForms 项目,我正在尝试通过使用 Web API 而不是 Code-Behind 上的传统 [WebMethod] 静态来实现现代化(因为它非常有限)。

但是,我也希望能够在 Web API 中读取会话 Cookie。之前,我可以通过访问HttpContext.Current.Session["NAME_OF_COOKIE_HERE"]然后将其转换为模型来在代码隐藏中阅读它——我不知道如何使用 Web API 来做到这一点。

我正在使用 axios 与我的 Web API 控制器通信。

我已将其添加withCredentials: true到我的 axios 配置中,但我该如何从那里继续前进?您如何准确地读取 Web API 控制器中的会话 cookie?

这是一个示例:

// Client for testing
axios.get(API_ENDPOINT_URL_HERE, {withCredentials: true}).then(res => res).catch(err => err);
// Web API Controller
[Route(API_ENDPOINT_URL_ACCESSIBLE_BY_THE_CLIENT_TESTING)]
[HttpGet]
public IHttpActionResult SOME_FUNCTION_NAME() {
  var currentUser = // I don't know what to do from here on.
}

标签: asp.net-web-apiwebformsaxios

解决方案


答案在这个链接中:ASP.NET Web API session 还是什么?

具体来说,在 Global.asax.cs 中添加以下内容

public override void Init()
{
    this.PostAuthenticateRequest += MvcApplication_PostAuthenticateRequest;
    base.Init();
}

void MvcApplication_PostAuthenticateRequest(object sender, EventArgs e)
{
    System.Web.HttpContext.Current.SetSessionStateBehavior(
        SessionStateBehavior.Required);
}

推荐阅读