如何在 Web API 控制器中读取 ASP.NET_SessionId?

How to read ASP.NET_SessionId in Web API Controllers?

我们有一个遗留的 ASP.NET WebForms 项目,我试图通过使用 Web APIs 而不是代码隐藏上的传统 [WebMethod] 静态来实现现代化(因为它非常有限).

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

我正在使用 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.
}

答案就在这个link中:ASP.NET Web API session or something?

具体来说,在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);
}

您可以通过 HttpRequestMessage.Headers 在 httpRequestMessage 中像任何 header 属性 一样读取 cookie。请按照 link 正确实施 WebAPI: Getting Headers, QueryString and Cookie Values 另请注意,如果您希望请求中有 cookie,则使用 "Cookie" header 键,如果您正在休息 api 调用并尝试在响应中查找 cookie,则使用 "Set-Cookie"