ASP.NET MVC 自定义Razor视图WorkContext

概述

1、在ASP.NET MVC项目开发的过程中,我们经常需要在cshtml的视图层输出一些公用信息 比如:页面Title、服务器日期时间、页面关键字、关键字描述、系统版本号、资源版本号等 2、普通的做法就是使用ViewBag.Title或ViewData["Title"] ,然后在视图层通过@ViewBag.Title进行输出 3、稍微高大尚一点的做法就是创建一个Model,视图层输出Model的属性,例如:@Model.Title 今天提供另外一个实践做法: ASP.NET MVC 自定义Razor视图上下文-WorkContext, 减少ViewBag、ViewData的使用

详细

一、实现背景

   我们在使用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的配置

示例截图:

QQ截图20171211152935.png

 

 

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、项目结构

QQ截图20171211152527.png

 

三、样式效果

 

QQ截图20171211152641.png

QQ截图20171211152714.png

四、代码截图

image.png

posted @ 2018-02-27 10:13  ^_^漂……  阅读(636)  评论(0编辑  收藏  举报