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

如何在ASP.NET Core Razor Pages中检查指定Razor视图是否存在

问题原因

你使用的ViewEngine.FindView默认遵循MVC视图的查找规则,仅扫描/Views/{ControllerName}、/Views/Shared、/Pages/Shared等预设目录,不会自动匹配Razor Pages目录下同层级的普通Razor视图,因此文件存在时也会返回false。

修复方案

方案1:使用GetView按相对路径查找(推荐)

直接基于当前执行的视图路径,传入同目录下的视图名即可,无需编写全路径:

// 在List.cshtml视图中直接使用
var viewResult = ViewEngine.GetView(
    executingFilePath: ViewContext.ExecutingFilePath, 
    viewPath: "Augmenter.cshtml", 
    isMainPage: false);
bool viewExists = viewResult.Success;

如果是在List.cshtml.cs对应的PageModel中调用,需要先注入IViewEngine服务:

public class ListModel : PageModel
{
    private readonly IViewEngine _viewEngine;

    public ListModel(IViewEngine viewEngine)
    {
        _viewEngine = viewEngine;
    }

    public void OnGet()
    {
        var viewResult = _viewEngine.GetView(ViewContext.ExecutingFilePath, "Augmenter.cshtml", false);
        bool viewExists = viewResult.Success;
    }
}

方案2:传入完整根路径调用FindView

直接填写视图从项目根开始的绝对路径,必须带.cshtml后缀:

var viewResult = ViewEngine.FindView(
    ViewContext, 
    "/Pages/Gallery/Augmenter.cshtml", 
    isMainPage: false);
bool viewExists = viewResult.Success;

内容的提问来源于stack exchange,提问作者Alireza Hosseinitabar

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.19 15:06:06