【问题标题】:Unable to access the HttpContext or Request object in the constructor of an AsyncController无法访问 AsyncController 的构造函数中的 HttpContext 或 Request 对象
【发布时间】:2015-08-07 17:42:28
【问题描述】:

我正在使用 AsyncController 说“AbstractAbcContoller”

public class AbstractAbcContoller : AsyncController
{
}

然后我还有 3 个控制器继承了新创建的 AbstractAbcContoller

现在,当我为这 3 个控制器中的任何一个创建构造函数并尝试访问 HttpContext/Request 对象时,我总是将它们设为 null。

我需要初始化接受 HttpRequestBase 作为其构造函数中的参数的服务对象。

我不得不接受这种解决方法。

public class AbstractAbcController : AsyncController
{
    protected IAbcService GetAbcService(AbstractAbcController controller, HttpRequestBase request)
    {
        if (controller.GetType() == typeof (AbcAddressVerificationController))
            return new AbcAddressVerificationService(request);

        if (controller.GetType() == typeof(AbcPhoneVerificationController))
            return new AbcPhoneVerificationService(request);

        throw new ArgumentException();
    }
}

然后在控制器/动作中使用类似这样的东西

IAbcService abcService = GetAbcService(this, Request);
abcService.DoSomething();

我有点不喜欢,我不确定哪种方法更好。请指教。

【问题讨论】:

    标签: c# asp.net-mvc-4 asynccontroller


    【解决方案1】:

    请求和响应上下文是每个请求对象,并且每个请求上下文都有一个单独的副本,因此通过构造函数注入它们没有意义,因此应该将它们传递给需要它们的每个方法的参数

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-11-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-24
      相关资源
      最近更新 更多