将HttpContext.Current.Session注入拦截器/或使用内部拦截器(mvc4 webapi)时,它为null

时间:2014-01-13 13:23:19

标签: asp.net-mvc-4 session asp.net-web-api castle-windsor

我有使用城堡温莎拦截的mvc4 WebAPI应用程序。
拦截器类需要HttpContext.Current.Session 当我直接从拦截器调用它时,它是空的 所以我在这里读到我需要注入Session而不只是在拦截器中访问它。

这个代码我最终得到了......

protected void Application_Start()
{
    ControllerBuilder.Current.SetControllerFactory(new WindsorControllerFactory(container.Kernel));
            this.RegisterDependencyResolver();
            this.container.Install(new WindsorWebApiInstaller());
}

public class WindsorWebApiInstaller : IWindsorInstaller
{

  public void Install(IWindsorContainer container, IConfigurationStore store)
  {
     // the following interceptor needs Session object
     container.Register( Component.For<IInterceptor>()
                     .ImplementedBy<SecurityInterceptor>()
                     .LifestylePerWebRequest()
                     .Named("SecurityInterceptor"));

     // session is null here, So Castle wont inject it and throw exception...
     container.Register(
         Component.For<HttpSessionStateBase>().UsingFactoryMethod( 
                   () => new HttpSessionStateWrapper(HttpContext.Current.Session)).LifestylePerWebRequest());
  }
}

还有其他方法可以从拦截器访问会话吗?

由于

1 个答案:

答案 0 :(得分:2)

我总是忘记WEBAPI不是MVC 这不是城堡问题。

这就是诀窍!

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

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

https://stackoverflow.com/a/15038669/936651
+1到@Soren

相关问题