在asp.net mvc razor页面模型中获取wwwroot/xxx/xxx.json文件的内容

在实现这个需求的时候这里有个大坑, 不知道是我自己框架搭得有问题,还是什么问题. 在 Razor模型中无法使用 System.IO, 左试右试,搞了半天, 你是大哥,最后放弃在Razor模型中读取wwwroot里面的配置文件, 我去其它地方写还不行哟, 
然后我就在当前解决方案下新建了一个Service文件夹-> 创建GetTemplate.cs

 

Razor页面模型

 GetTemplate.cs

using IdentityServer.Models;

namespace IdentityServer.Service
{
    /// <summary>
    /// 获取模版数据
    /// </summary>
    public class GetConfigData
    {
        private readonly IWebHostEnvironment _env;
        public TemplateConfig Config { get; set; }
        public GetConfigData(IWebHostEnvironment env)
        {
            _env = env;
        }
        public TemplateConfig GetTemplate()
        {
            // 组合文件路径
            string configPath = Path.Combine(
                _env.WebRootPath,
                "configs",
                "defaultConfig.json"
            );

            // 读取文件内容
            var jsonContent = System.IO.File.ReadAllText(configPath);

            // 反序列化为实体
            Config = JsonConvert.DeserializeObject<TemplateConfig>(jsonContent);
            return Config;
        }
    }
}

然后在Razor页面模型中就行调用, 然后你就能获取到文件中的内容了

using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Hosting;
using System.IO;
using System.Text.Json;

public class YourPageModel : PageModel
{public YourPageModel(IWebHostEnvironment env)
    {
    var data = new GetConfigData(env).GetTemplate(); } }

 

posted @ 2025-03-18 17:37  龙卷风吹毁停车场  阅读(16)  评论(0)    收藏  举报