I have an ASP.NET Web API project and I need to access session HttpContext.Current.Session
but it's always null in web api
accoriding to Accessing Session Using ASP.NET Web API question I need Application_PostAuthorizeRequest event.
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);
}
}
but the problem is Application_PostAuthorizeRequest event never fires. I recently upgraded my project from MVC4 to MVC5.
I can only catch Application_AuthenticateRequest but when I copy the same code in this event it doesn't help and session is still null
Update:
I'm using SignalR to send instant notifications.
I found out when I comment this line app.MapSignalR()
eveything works as I expected and I can catch the event.
Startup.cs:
[assembly: OwinStartup(typeof(Startup))]
namespace UI
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
HttpConfiguration config = new HttpConfiguration();
ConfigureOAuth(app);
WebApiConfig.Register(config);
app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
app.UseWebApi(config);
//app.MapSignalR(); when i comment this line I can catch the event
}
public void ConfigureOAuth(IAppBuilder app)
{
OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
{
AllowInsecureHttp = true,
TokenEndpointPath = new PathString("/token"),
// TODO expired time hardcoded
AccessTokenExpireTimeSpan = TimeSpan.FromHours(24),
Provider = new SimpleAuthorizationServerProvider(),
RefreshTokenProvider = new SimpleRefreshTokenProvider()
};
// Token Generation
app.UseOAuthAuthorizationServer(OAuthServerOptions);
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
}
}
}
can somebody explain what's wrong? why when I comment app.MapSignalR()
everything works fine.
Any help will be greatly appreciated!