Asp.net web api 如何在Web API控制器中读取ASP.NET_会话ID?

Asp.net web api 如何在Web API控制器中读取ASP.NET_会话ID?,asp.net-web-api,webforms,axios,Asp.net Web Api,Webforms,Axios,我们有一个遗留的ASP.NET WebForms项目,我正试图通过使用Web API而不是传统的[WebMethod]代码隐藏静态(因为它非常有限)来实现它的现代化 但是,我也希望能够在Web API中读取会话Cookie。以前,我可以通过访问HttpContext.Current.Session[“NAME\u OF_COOKIE\u HERE”]在代码背后阅读它,然后将它转换为一个模型-我不知道如何使用Web API实现这一点 我正在使用axios与我的Web API控制器通信 我已经在ax

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

但是,我也希望能够在Web API中读取会话Cookie。以前,我可以通过访问HttpContext.Current.Session[“NAME\u OF_COOKIE\u HERE”]在代码背后阅读它,然后将它转换为一个模型-我不知道如何使用Web API实现这一点

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

我已经在axios配置中添加了
with credentials:true
,但是如何继续?如何准确读取Web API控制器中的会话cookie

以下是一个示例:

// Client for testing
axios.get(API_ENDPOINT_URL_HERE, {withCredentials: true}).then(res => res).catch(err => err);

答案在这个链接中:

具体来说,在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。请使用正确的实现跟随链接 另外请注意,如果您希望在请求中使用cookie,则使用“cookie”头键;如果您正在进行rest api调用并尝试在响应中查找cookie,则使用“Set cookie”

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

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