1

I am trying to use session variables in my web api non mvc application.

I have enabled session in global.aspx page as

protected void Application_PostAuthorizeRequest()
        {
            HttpContext.Current.SetSessionStateBehavior(SessionStateBehavior.Required);
        }

Now in my controller

public class AuthenticateController : ApiController
{
[Route("api/CheckLogin")]
public string AuthenticateUser(Models.Customer customer)
{

HttpContextBase context = null;
var httpContext = context as HttpContextBase;
httpContext.Session["username"] = "sa";

}

But I am getting null ref error.

How can I achieve this

Please help

user2363957
  • 93
  • 1
  • 11
  • Let me get this straight: you create a variable called `context`, set it equal to `null`, cast that null value as an `HttpContextBase`, and then try to use it? At some point you have to actually set it equal to the current context, or at least set it to some non-null value. I.e. `context = HttpContext.Current;`. – TheRotag Apr 19 '16 at 17:36
  • You don't need the `HttpContextBase context = null;` line. And you need to check that httpContext is non null before using it. The `as` can return null if the object you're trying to cast is not of type HttpContextBase. After that, you'll need to check that username has been correctly set in the session. Debug it by checking that value for null, on retrieval from your Session object. – ManoDestra Apr 19 '16 at 17:45
  • I did like this object context; if (Request.Properties.TryGetValue("MS_HttpContext", out context)) { var httpContext = context as HttpContextBase; if (httpContext != null && httpContext.Session != null) { httpContext.Session["d"] = "sa"; } } – user2363957 Apr 19 '16 at 18:53

1 Answers1

-1

Well the context is set to null . So basically you are executing null.Session["username"] ! But why do you need a session in this implementtaion. This is a REST service right ? Its supposed to be stateless. See this excellent answer here : Link

Community
  • 1
  • 1
Som Bhattacharyya
  • 3,972
  • 35
  • 54