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.
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.
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
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);
}
}
}