0

Using MVC

Naturally, after authentication in a Web API, I want to assign session("LoggedIn") the value True.

But the session in my Web API keeps returning NullReference.

Any workaround?

Thanks.

HelpASisterOut
  • 3,085
  • 16
  • 45
  • 89
  • This will help you surely. http://stackoverflow.com/questions/11478244/asp-net-web-api-session-or-something – K D Jul 04 '14 at 14:39

2 Answers2

0

WebApiConfig.cs

public static class WebApiConfig
    {
        public static string UrlPrefix         { get { return "api"; } }
        public static string UrlPrefixRelative { get { return "~/api"; } }

        public static void Register(HttpConfiguration config)
        {
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: WebApiConfig.UrlPrefix + "/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
    }

Global.asax.cs

public class MvcApplication : System.Web.HttpApplication
{
    ...

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

    private bool IsWebApiRequest()
    {
        return HttpContext.Current.Request.AppRelativeCurrentExecutionFilePath.StartsWith(WebApiConfig.UrlPrefixRelative);
    }

}

for more details Accessing Session Using ASP.NET Web API

Community
  • 1
  • 1
Ondipuli
  • 468
  • 3
  • 9
  • http://stackoverflow.com/questions/9594229/accessing-session-using-asp-net-web-api – K D Jul 04 '14 at 14:39
0

You need to Sets the type of session state behavior that is required in order to support an HTTP request.

You can do the changes in Application_PostAuthorizeRequest() in Global.asax file.

using System.Web.Http;
using System.Web;
using System.Web.SessionState;

namespace Sample
{
    public class WebApiApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            WebApiConfig.Register(GlobalConfiguration.Configuration);
        }

        protected void Application_PostAuthorizeRequest()
        {           
            HttpContext.Current.SetSessionStateBehavior(SessionStateBehavior.Required);           
        }       
    }
}
Saravana Kumar
  • 3,669
  • 5
  • 15
  • 35