概述
详细
一、实现背景
我们在使用ASP.NET MVC+Razor视图做WEB项目的时候大家或许都有这样的需求:
1、我们需要在每个Action中获取一些Request请求的一些公用信息
比如:
IsAjax 当前是否为Ajax请求
CurrentUserId 当前登录用户Id (从Cookie中或Session中获取)
IsSuperAdministrator 当前是否为超级管理员(拿到CurrentUserId后从DB或缓存中获取)
......
2、我们需要从后台输出一些公共信息至页面上
比如:
ResourcesVersion 资源文件版本号
ServerDateTimeString 系统日期时间(字符串类型)
SiteTitle 站点标题
......
常规做法:
接收的话我们通常会创建一个父类控制器或公共方法,来获取或设置这些信息
输出的话我们通常做法是使用 ViewBag.SiteTitle 或ViewData["SiteTitle"] 来设置与视图的模型数据,
然后在Razor视图中使用@ViewBag.SiteTitle 或@ViewData["SiteTitle"] 来显示输出
今天我们来实践另外一种比较简洁的做法(个人认为比较简洁且易扩展):通过自定义WebWorkContext来实践刚才的两点需求。创建自定义上下文和基类控制器 重写System.Web.Mvc.WebViewPage来实践。
二、程序实现
1、创建上下文类:WebWorkContext
namespace Mvc.WorkContext.WorkContexts { public class WebWorkContext { /// <summary> /// 当前url /// </summary> public string Url; /// <summary> /// 当前是否为ajax请求 /// </summary> public bool IsHttpAjax = false; /// <summary> /// 当前系统版本号 /// </summary> public string Version = "1.0"; /// <summary> /// 资源文件版本号 /// </summary> public string ResourcesVersion = "2016.07.11.01"; /// <summary> /// 开始执行时间 /// </summary> public DateTime StartExecuteTime; /// <summary> /// 页面执行时长 /// </summary> public double ExecuteTime; /// <summary> /// 系统日期时间(日期类型) /// </summary> public DateTime ServerDateTime = DateTime.Now; /// <summary> /// 系统日期时间(字符串类型) /// </summary> public string ServerDateTimeString = ""; /// <summary> /// 系统日期(字符串类型) /// </summary> public string ServerDateString = ""; /// <summary> /// 站点标题 /// </summary> public string SiteTitle = "-"; /// <summary> /// 关键字 /// </summary> public string SiteKeywords = ""; /// <summary> /// 关键字描述 /// </summary> public string SiteDescription = ""; } }
备注:上下文类里面的属性可根据自己项目的实际情况进行删减,比如可以添加一些当前会话相关的信息:CurrentUserId、CurrentUserName等
2、创建BaseController
namespace Mvc.WorkContext.Controllers { public class BaseController : Controller { public WebWorkContext WorkContext = new WebWorkContext(); protected override void Initialize(System.Web.Routing.RequestContext requestContext) { base.Initialize(requestContext); this.ValidateRequest = false; WorkContext.Url = System.Web.HttpContext.Current.Request.Url.ToString(); if (System.Web.HttpContext.Current != null && System.Web.HttpContext.Current.Request != null) { WorkContext.IsHttpAjax = System.Web.HttpContext.Current.Request.Headers["X-Requested-With"] == "XMLHttpRequest"; } WorkContext.ServerDateTime = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")); WorkContext.ServerDateTimeString = WorkContext.ServerDateTime.ToString("yyyy-MM-dd HH:mm:ss"); WorkContext.ServerDateString = WorkContext.ServerDateTime.Date.ToString("yyyy-MM-dd"); } protected override void OnAuthorization(AuthorizationContext filterContext) { base.OnAuthorization(filterContext); if (filterContext.IsChildAction) return; if (WorkContext.IsHttpAjax) { } else { } } protected override void OnActionExecuting(ActionExecutingContext filterContext) { base.OnActionExecuting(filterContext); if (filterContext.IsChildAction) return; //页面开始执行时间 WorkContext.StartExecuteTime = DateTime.Now; } protected override void OnActionExecuted(ActionExecutedContext filterContext) { base.OnActionExecuted(filterContext); //页面执行时长 WorkContext.ExecuteTime = DateTime.Now.Subtract(WorkContext.StartExecuteTime).TotalMilliseconds / 1000; } } }
备注: 1、 在BaseController中全局实例WebWorkContext对象为WorkContext
2、 在BaseController里面可在Initialize方法中对WorkContext各属性进行赋值
3、自定义WebViewPage 继承自System.Web.Mvc.WebViewPage
namespace Mvc.WorkContext.WebViewPages { /// <summary> /// Razor 视图所需的属性和方法。 /// </summary> public abstract class WebViewPage<TModel> : System.Web.Mvc.WebViewPage<TModel> { public WebWorkContext WorkContext; public override void InitHelpers() { base.InitHelpers(); if (this.ViewContext.Controller is BaseController) { WorkContext = ((BaseController)(this.ViewContext.Controller)).WorkContext; } } } /// <summary> /// Razor 视图所需的属性和方法。 /// </summary> public abstract class WebViewPage : WebViewPage<dynamic> { } }
这里重点是重写InitHelpers方法,将BaseController中的WorkContext属性赋值给WebViewPage中定义的WorkContext属性
4、创建业务控制器HomeController 继承自:BaseController
namespace Mvc.WorkContext.Controllers { public class HomeController : BaseController { // // GET: /Home/ public ActionResult Index() { WorkContext.SiteTitle = "ASP.NET MVC 自定义Razor视图上下文 -DEMO演示首页"; return View(); } } }
在各个业务控制器的Action中可以直接 Get/Set WorkContext中的属性
5、配置View/web.config
<system.web.webPages.razor> <host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" /> <!-- 替换原有的pageBaseType为自定义的WebViewPage <pages pageBaseType="System.Web.Mvc.WebViewPage"> --> <pages pageBaseType="Mvc.WorkContext.WebViewPages.WebViewPage"> <namespaces> <add namespace="System.Web.Mvc" /> <add namespace="System.Web.Mvc.Ajax" /> <add namespace="System.Web.Mvc.Html" /> <add namespace="System.Web.Routing" /> </namespaces> </pages> </system.web.webPages.razor>
配置Views/web.config 中的system.web.webPages.razor->pageBaseType的配置
示例截图:
6、在cshtml视图中使用WebWorkContext对象中的属性
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>@WorkContext.SiteTitle</title> <meta name="keywords" content="@WorkContext.SiteKeywords" /> <meta name="description" content="@WorkContext.SiteDescription" /> <link href="/Content/css/css.css?r=@WorkContext.ResourcesVersion" rel="stylesheet"/> </head> <body> <h1> <a href="/List/Index">GOTO List</a> </h1> <table width="100%" border="0"> <caption>@WorkContext.SiteTitle</caption> <tr> <td>序号</td> <td>属性</td> <td>值</td> </tr> <tr> <td>1</td> <td>Url</td> <td>@WorkContext.Url</td> </tr> <tr> <td>2</td> <td>IsHttpAjax</td> <td>@WorkContext.IsHttpAjax</td> </tr> <tr> <td>3</td> <td>Version</td> <td>@WorkContext.Version</td> </tr> <tr> <td>4</td> <td>ResourcesVersion</td> <td>@WorkContext.ResourcesVersion</td> </tr> <tr> <td>5</td> <td>StartExecuteTime</td> <td>@WorkContext.StartExecuteTime</td> </tr> <tr> <td>6</td> <td>ExecuteTime</td> <td>@WorkContext.ExecuteTime</td> </tr> <tr> <td>7</td> <td>ServerDateTime</td> <td>@WorkContext.ServerDateTime</td> </tr> <tr> <td>8</td> <td>ServerDateTimeString</td> <td>@WorkContext.ServerDateTimeString</td> </tr> <tr> <td>9</td> <td>ServerDateString</td> <td>@WorkContext.ServerDateString</td> </tr> <tr> <td>10</td> <td>SiteTitle</td> <td>@WorkContext.SiteTitle</td> </tr> <tr> <td>11</td> <td>SiteKeywords</td> <td>@WorkContext.SiteKeywords</td> </tr> <tr> <td>12</td> <td>SiteDescription</td> <td>@WorkContext.SiteDescription</td> </tr> </table> </body> </html>
7、项目结构