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

如何在ASP.NET Core应用内访问配置选项?

获取MVC视图查找路径并输出

我的尝试

HelloWorldController.cs

public class HelloWorldController : Controller
{
    public string Index()
    {
        StringBuilder output = new StringBuilder();

        // 我该怎么实现?
        IConfiguration configuration = app.Configuration;
        List<String> list = configuration.options.ViewLocationExpanders;

        foreach(String item in list)
        {
            output.Append(HtmlEncoder.Default.Encode($"Looking in " + item));
        }

        return output.ToString();
    }
    ...
}

遇到的问题

无法编译

期望结果

访问 https://localhost:7127/HelloWorld 时输出:

Looking in /Views/HelloWorld/Index.cshtml
Looking in /Views/Shared/Index.cshtml
Looking in /Pages/Shared/Index.cshtml

正确实现方法

你的代码错误在于试图从IConfiguration获取视图位置扩展器,实际上MVC的视图查找路径需要通过视图引擎服务获取,以下是可行的实现:

using System.Text;
using System.Text.Encodings.Web;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ViewEngines;

public class HelloWorldController : Controller
{
    private readonly ICompositeViewEngine _viewEngine;

    // 通过构造函数注入视图引擎服务
    public HelloWorldController(ICompositeViewEngine viewEngine)
    {
        _viewEngine = viewEngine;
    }

    public string Index()
    {
        var output = new StringBuilder();
        var controllerName = ControllerContext.ActionDescriptor.ControllerName;
        var actionName = ControllerContext.ActionDescriptor.ActionName;

        // 获取视图的所有候选查找路径
        var searchLocations = _viewEngine.FindView(ControllerContext, actionName, controllerName, false).SearchLocations;

        foreach (var location in searchLocations)
        {
            output.AppendLine(HtmlEncoder.Default.Encode($"Looking in {location}"));
        }

        return output.ToString();
    }
}

说明

  1. 控制器通过构造函数注入ICompositeViewEngine——这是MVC负责查找视图的核心服务。
  2. 调用FindView方法并传入当前上下文、动作名和控制器名,通过SearchLocations属性获取所有待查找的视图路径。
  3. 遍历路径并编码输出,即可得到你期望的结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 03:26:13