asp.net-web-api - 如何在 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 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);
}
推荐阅读
- c - ROT13编码的C程序
- javascript - Console.log 打印数据但函数不返回数据
- python - 如何使我的函数输出成为熊猫数据框?
- python - Python Selenium - send_keys 不向元素发送任何信息
- neo4j - 在自定义密码查询期间设置属性
- amazon-web-services - 如何遍历 s3 存储桶列表并为每个存储桶创建和附加许多策略?
- python - 使用python中的函数将数组附加到数组
- scheme - 如何将一个列表变成多个返回值?
- python - python检查登机时间-如果不是45分钟,则计算等待多长时间
- c# - 如何将具有唯一字段的两个不同对象列表合并到单独的列表中?