Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

asp.net mvc - Where to use Controller.HttpContext

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

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

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.

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?).

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

Thanks Ben

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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);
  }
}

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...