【问题标题】:HttpContext.Current.Session is null when injecting it to interceptor / or using in inside interceptor (mvc4 webapi)将HttpContext.Current.Session注入拦截器/或在拦截器内部使用时为空(mvc4 webapi)
【发布时间】:2014-01-13 13:23:19
【问题描述】:

我有 mvc4 WebAPI 应用程序与城堡 Windsor 拦截。
拦截器类需要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());
  }
}

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

谢谢

【问题讨论】:

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


    【解决方案1】:

    我总是忘记 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

    【讨论】:

      猜你喜欢
      • 2014-02-09
      • 1970-01-01
      • 1970-01-01
      • 2015-11-22
      • 2014-03-10
      • 1970-01-01
      • 1970-01-01
      • 2013-06-25
      • 2018-08-09
      相关资源
      最近更新 更多