【问题标题】:MVC 4 with Castle Windsor IOC Controllers Session Is Null带有 Castle Windsor IOC 控制器会话的 MVC 4 为空
【发布时间】:2016-07-18 08:17:40
【问题描述】:

我有一个 MVC4 解决方案,它有一个单独的控制器项目。这一切都很好。

我现在已经集成了 Castle Windsor IOC,就像我之前在单个项目解决方案中做过很多次一样,它似乎已经正确注册,因为当我的网站启动时,它调用 HomeController 并带有存储库依赖项就好了。

然而,我所有的控制器都继承了一个 BaseController 类(它自然地继承了 Controller),并且在 BaseController 的构造函数中,我正在访问 Session 对象。

发布温莎城堡后,这不再有效。 Session 对象为空。

这是来自 BaseController 的代码

    protected BaseController(ICustomerRepository customerRepository, ISystemSettingsRepository systemSettingsRepository)
    {
        _customerRepository = customerRepository;
        _systemSettingsRepository = systemSettingsRepository;

        _timeoutMinutes = _systemSettingsRepository.GetSystemSettings().TimeoutMinutes;

        Session["KYCWarning"] = _customerRepository.GetMessage("KYCWarning");
    }

我将此消息存储在 Session 变量中的原因是它用于 cshtml 文件的条件语句中

@{
    var kycWarning = Session["KYCWarning"].ToString();
    var settingShowKYCReminder = ConfigurationManager.AppSettings["ShowKYCReminder"];
    var showKYCReminder = !string.IsNullOrWhiteSpace(settingShowKYCReminder) && (bool.Parse(settingShowKYCReminder));
}

@if (showKYCReminder && Session["CurrentSession"] != null && !string.IsNullOrWhiteSpace(kycWarning) && !((SessionModel)Session["CurrentSession"]).Customer.KycAuthorised)
{
    <div class="">
        <div class="col-md-12 WarningMessageBox">
            <span>@kycWarning</span>
        </div>
    </div>
}

这只是一个示例,控制器中还有其他 Session 用途,如果代码在此异常之后可以访问,我预计它们将失败。

任何人都可以提出为什么会发生这种情况,以及解决方案吗?我知道继承 Controller 类的控制器总是可以访问 Session。

谢谢。

【问题讨论】:

  • 除此之外 - 我已将单独的控制器项目移回主 Web 项目,因为实际上不再需要它在那里。同样的问题仍然存在。

标签: c# asp.net-mvc session inversion-of-control castle-windsor


【解决方案1】:

好吧,问题出在我身上,而不是 Castle.Windsor!

我在构造函数中访问 Session,当然这是由 Castle Windsor 在 Session 对象不一定可用的时候调用的。

我将设置会话变量的代码移到应用程序的另一部分,其他代码在控制器中使用 Session 时一切正常。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-18
    相关资源
    最近更新 更多