ASP.NET MVC 自定义Razor视图WorkContext
概述
详细
一、实现背景
我们在使用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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 | 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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 | 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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | 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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | 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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | <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对象中的属性
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 | <! 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、项目结构
三、样式效果
四、代码截图
注:本文著作权归作者,由demo大师发表,拒绝转载,转载需要作者授权
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· 使用C#创建一个MCP客户端
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· Windows编程----内核对象竟然如此简单?