asp.net-mvc – ASP.NET MVC如何在生产中禁用调试路由/视图?

我需要创建一些辅助控制器操作和相关视图,我希望能够(有条件地?)在生产中禁用.

一种方法是在RegisterRoutes()体中的特定路径周围使用#ifdef DEBUG pragma,但这根本不灵活.

web.config中的设置也一样好,但我不知道如何解决这个问题.

已建立的“插件”项目如Glimpse或Phil Haack的旧版Route Debugger如何做到这一点?

我宁愿做一些比YAGNI更简单的事……

解决方法

你也可以使用过滤器,例如把这个类扔到某个地方:
public class DebugOnlyAttribute : ActionFilterattribute
    {
        public override void OnActionExecuting(
                                           ActionExecutingContext filterContext)
        {
             #if DEBUG
             #else
                 filterContext.Result = new HttpNotFoundResult();
             #endif
        }
    }

然后你就可以直接进入控制器并使用[DebugOnly]装饰你不需要在生产中显示的动作方法(或整个控制器).

您也可以使用filterContext.HttpContext.IsDebuggingEnabled而不是uglier #if DEBUG我只是倾向于使用预编译器指令,因为决定肯定不会采用任何cpu周期.

如果您希望全局过滤器针对几个URL检查所有内容,请将其注册为Global.asax中的全局过滤器:

public static void RegisterGlobalFilters(GlobalFilterCollection filters) {

    filters.Add(new DebugActionFilter());
}

然后你可以检查URL或你想要的任何列表(这里显示的应用程序相对路径):

public class DebugActionFilter : IActionFilter
{
    private List<string> DebugUrls = new List<string> {"~/Home/","~/Debug/"}; 
    public void OnActionExecuting(ActionExecutingContext filterContext)
    {
        if (!filterContext.HttpContext.IsDebuggingEnabled 
            && DebugUrls.Contains(
                      filterContext
                     .HttpContext
                     .Request
                     .AppRelativeCurrentExecutionFilePath))
        {
            filterContext.Result = new HttpNotFoundResult();
        }
    }

    public void OnActionExecuted(ActionExecutedContext filterContext)
    {
    }
}

相关文章

### 创建一个gRPC服务项目(grpc服务端)和一个 webapi项目(...
一、SiganlR 使用的协议类型 1.websocket即时通讯协议 2.Ser...
.Net 6 WebApi 项目 在Linux系统上 打包成Docker镜像,发布为...
一、 PD简介PowerDesigner 是一个集所有现代建模技术于一身的...
一、存储过程 存储过程就像数据库中运行的方法(函数) 优点:...
一、Ueditor的下载 1、百度编辑器下载地址:http://ueditor....