You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在无控制器场景下向.NET Framework 4.6.1 MVC视图传递数据

针对.NET Framework 4.6.1 MVC 项目给NotFoundMVC包生成的NotFound视图传参的解决方案

下面提供3种不同复杂度的实现方案,可根据自身业务需求选择:


方案1:注册全局Action过滤器注入共享数据(推荐,符合MVC规范)

该方案无需修改原有视图或包配置,通过全局过滤器自动识别404响应并注入数据:

  1. 新建过滤器类,引用System.Web.Mvc命名空间:
public class NotFoundViewDataFilter : IActionFilter
{
    public void OnActionExecuting(ActionExecutingContext filterContext)
    {
        // 无需处理Action执行前逻辑
    }

    public void OnActionExecuted(ActionExecutedContext filterContext)
    {
        var viewResult = filterContext.Result as ViewResult;
        // 同时匹配NotFound视图名和404状态码,兼容不同场景
        if (viewResult != null 
            && (viewResult.ViewName == "NotFound" || filterContext.HttpContext.Response.StatusCode == 404))
        {
            // 按需求注入Layout需要的任意数据
            filterContext.Controller.ViewData["PageTitle"] = "404 页面不存在";
            filterContext.Controller.ViewBag.HideSideBar = true;
            filterContext.Controller.ViewData["StatisticPageId"] = "error_404";
        }
    }
}
  1. 在App_Start/FilterConfig.cs中注册全局过滤器:
public class FilterConfig
{
    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(new HandleErrorAttribute());
        // 新增行注册自定义过滤器
        filters.Add(new NotFoundViewDataFilter());
    }
}
  1. 直接在Layout.cshtml中正常读取ViewData/ViewBag的值即可,和普通控制器传参用法完全一致。

方案2:直接在NotFound.cshtml中赋值(快速实现简单需求)

如果传递的数据逻辑非常简单,不需要后端服务处理,可以直接在~/Views/Shared/NotFound.cshtml顶部添加Razor代码块赋值,数据会直接传递给关联的Layout:

@{
    Layout = "~/Views/Shared/_Layout.cshtml";
    // 直接在这里赋值需要的参数
    ViewData["PageTitle"] = "404 页面不存在";
    ViewBag.ShowFooter = false;
}

方案3:接管404处理逻辑(灵活度最高,适合复杂业务场景)

如果需要做更多自定义处理,可以直接替换NotFoundMVC的默认响应逻辑,自己用控制器处理404请求:

  1. 在Web.config的appSettings节点添加配置,禁用NotFoundMVC默认处理器:
<add key="NotFoundMVC.DisableHandler" value="true" />
  1. 新增Error控制器,添加NotFound Action,自定义传参逻辑:
public class ErrorController : Controller
{
    public ActionResult NotFound()
    {
        // 这里可以调用任意服务层逻辑获取数据
        ViewData["PageTitle"] = "404 页面不存在";
        ViewBag.RecommendPages = _pageService.GetRecommendPages();
        // 返回包生成的NotFound视图
        return View("~/Views/Shared/NotFound.cshtml");
    }
}
  1. 在Web.config的system.web节点配置404跳转规则:
<customErrors mode="On">
  <error statusCode="404" redirect="~/Error/NotFound" />
</customErrors>

内容的提问来源于stack exchange,提问作者Saeed Noruzi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.08 08:06:04