1
votes

My MVC4(beta) Azure WebRole has Controllers for WebApi access. This works fine, except for one small catch: it appears that Global.asax.cs Session_Start is only being called when I access a MVC page (HomeController, for example).

The scenario: My WebApi controllers need access to (in process) Session State storage. I access the Session State object in Start_Session and cache it for use by the WebApi Controllers. This works fine, as long as I access a single MVC-Web-Page first, but if I access the WebApi first, my Session State cache is not initialized, but apparently the routing table is, so Global.asax is being accessed.

Any tips on the initialization or Session State access in this scenario? I need to access the WebApi controllers without first accessing a web page...

Thanks! R

2

2 Answers

3
votes

In Global.asax

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

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

Here is forum post on ASP.NET - Enabling Session that shows how to enable Session State for WebApi calls using the PostAuthorizeRequest method. I have included the code snippet below modifications to the Global.asax file for your reference.

private const string _WebApiPrefix = "api";
private static string _WebApiExecutionPath = String.Format("~/{0}", _WebApiPrefix);

public static void RegisterRoutes(RouteCollection routes)
{
  routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

  routes.MapHttpRoute(
      name: "DefaultApi",
      routeTemplate: String.Format("{0}/{{controller}}/{{id}}", _WebApiPrefix),
      defaults: new { id = RouteParameter.Optional }
  );

}

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

private static bool IsWebApiRequest()
{
  return HttpContext.Current.Request
       .AppRelativeCurrentExecutionFilePath.StartsWith(_WebApiExecutionPath);
}

Looks like this should solve your issue.