Where to use Controller.HttpContext

99封情书 提交于 2019-11-29 13:11:13

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

If testability is your concern, I would wrap up the access to HttpContext with an interface and resolve it/inject it into your controller.

public class CookieValidator : ICookieValidator
{
   private HttpContext _Context;
   public HttpContext Context
   {
      get
      {
         if(_Context == null)
         {
             _Context = HttpContext.Current;
         }
         return _Context;
      }
      set  // set a mock here when unit testing
      {
         _Context = value;
      }
   }

public bool HasValidCookies() { _Context... // do your logic here } }

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!