将所有视图重定向到一个视图(例如UnderConstructionView)的最佳方法

Stu*_*rla 2 web-config asp.net-mvc-routing asp.net-mvc-3

有可能以某种方式将所有视图路由到一个特定视图吗?我希望有一个"Under Construction view",它始终是默认视图,直到我"翻转开关"而不必构建.在此之前,所有其他控制器操作都会路由到此视图

我很想知道我是否可以在web.config中完成它,或者如果我必须在Global.asax中的RegisterRoutes中有一些if/else.

Yor*_*rgo 8

您可以编写一个自定义过滤器属性,该属性从web.config中读取标记并将请求重定向到构建页面下.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Configuration;

namespace MyApp
{
    public class UnderConstAttribute : ActionFilterAttribute
    {
        private readonly static AppSettingsReader _reader;
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
              _reader = new AppSettingsReader();
              if(_reader.GetValue("UnderConst", typeof(bool)))
                 filterContext.HttpContext.Response.Redirect("/Underconst.html");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

你必须添加web.config文件的密钥

<appSettings><add key="UnderConst" value="false"/></appSettings>
Run Code Online (Sandbox Code Playgroud)

并且您必须将此过滤器添加到global.asax文件中的全局操作过滤器集合

  • 只是一个更新.为了使你的代码工作,我必须在if语句的开头删除readonly和(bool)强制转换,如果是((bool)_reader.GetValue("UnderConst",typeof(bool))). (3认同)

Jam*_*xon 7

将一个调用的文件app_offline.htm放入目录的根目录,这将显示所有请求.

删除(或重命名)此文件后,您的Web请求将照常处理.