0

We have a legacy ASP.NET WebForms project that I am trying to modernize by using Web APIs instead of the traditional [WebMethod] statics on Code-Behind (because it is just so limited).

However, I wanted to be able to read the Session Cookie in the Web API as well. Before, I can read it in the Code-Behind by accessing the HttpContext.Current.Session["NAME_OF_COOKIE_HERE"] and then casting it to a Model - I don't know how to do this with Web APIs.

I'm using axios to talk to my Web API Controllers.

I've added the withCredentials: true to my axios config but how do I move forward from there? How exactly can you read the session cookie in Web API Controllers?

Here's a sample:

// 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.
}
johnmikelridzz
  • 340
  • 1
  • 2
  • 12

2 Answers2

0

The answer is in this link: ASP.NET Web API session or something?

Specifically, adding the following in the 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);
}
johnmikelridzz
  • 340
  • 1
  • 2
  • 12
0

You can read cookie just like any header property in httpRequestMessage by HttpRequestMessage.Headers .Please follow the link with proper implementation WebAPI: Getting Headers, QueryString and Cookie Values Also please note that if you expect a cookie in the Request then use "Cookie" header key and if you are making an rest api call and trying to find cookie in response then use "Set-Cookie"