MVC Controller 基类 BaseController 中的 Request

今天修复mvc中的一个bug,需求是每个页面要获取当前URL链接中 host首是否正确,我把获取url的方法写到了Controller的基类BaseController(BaseController继承自Controller),所以在mvc中写了下面的代码。

public class HomeController : BaseController 
{
......
}
 
public class BaseController : Controller
{
        public BaseController ()
        {
                if (Request==null ) //Request的值始终为null
                {
                    ......
                }
        }
}

解决办法:

public class BaseController : Controller
{

// 在调用操作方法前调用。
  protected override void OnActionExecuting(ActionExecutingContext ctx)
        {
            base.OnActionExecuting(ctx);
                    if (Request == null)
                    {
                             ......
                    }
        }

// 在调用操作方法后调用。
   protected override void OnActionExecuted(ActionExecutedContext ctx)
       {
            base.OnActionExecuted(ctx);
                        if (Request==null )
                        {
                            ......
                        }
        }
}

根据需要选择。

posted @ 2018-08-22 11:21  Sky&Lion  阅读(3159)  评论(0编辑  收藏  举报