凡使用Controller.HttpContext [英] Where to use Controller.HttpContext

查看:559
本文介绍了凡使用Controller.HttpContext的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的基地控制器的构造函数,我呼吁,检查客户端上的特定的cookie的扩展方法。

In my base controller's constructor I am calling an extension method that checks for specific cookies on the client.

目前我使用System.Web.HttpContext.Current获取当前上下文。

Currently I am using System.Web.HttpContext.Current to get the current context.

不过,我带领相信我应该使用Controller.HttpContext,因为它更容易测试,并包含有关请求的其他信息。

However, I am lead to believe that I should be using Controller.HttpContext since it is more testable and contains additional information about the request.

不过,Controller.HttpContext返回在创建空(相信这是由设计),而且在初始化和Execute方法(除非我用Routing.RequestContext.HttpContext?)。

However, Controller.HttpContext returns null on creation (believe this is by design) but also on Initialize and Execute methods (unless I use Routing.RequestContext.HttpContext?).

所以,如果我应该使用代替HttpContext.Current Controller.HttpContext,在什么时候,是在一个请求?

So if I should be using Controller.HttpContext instead of HttpContext.Current, at what point is it available to me in a request?

谢谢

推荐答案

当你调用你的控制器内的操作方法你可以得到你Controller.HttpContext。因此,这意味着,你可以访问它的操作方法在

You can get your Controller.HttpContext when you invoke an action method inside your controller. So that means that you can access it inside an action method

如果您要检查在每次请求也许你可以使用自定义属性看看下面这个例子:

if you want to check that on every request maybe you can use an custom attribute look at this example:

public class LoggingFilterAttribute : ActionFilterAttribute
{
  public override void OnActionExecuting(ActionExecutingContext filterContext)
  {
    filterContext.HttpContext.Trace.Write("(Logging Filter)Action Executing: " +
        filterContext.ActionDescriptor.ActionName);

    base.OnActionExecuting(filterContext);
  }

  public override void OnActionExecuted(ActionExecutedContext filterContext)
  {
    if (filterContext.Exception != null)
        filterContext.HttpContext.Trace.Write("(Logging Filter)Exception thrown");

    base.OnActionExecuted(filterContext);
  }
}

我建议你在自定义属性读了。但是,你是什么意思更多的可测试?您可以轻松地像犀牛嘲笑或谷歌MOQ嘲弄嘲弄框架您的HttpContext

I suggest you read up on custom attributes. But what do you mean with more testable? You can easily mock your httpcontext with a mocking framework like rhino mocks or google moq

这篇关于凡使用Controller.HttpContext的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆