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

如何在ASP.NET Core管理后台对.resx文件执行CRUD操作?

在ASP.NET Core管理后台实现.resx文件CRUD操作

一、基础准备

  1. 确认.resx文件存放路径(通常是项目根目录下的Resources文件夹),给应用程序池配置该文件夹的读写权限,避免文件访问失败。
  2. 确保项目已引用System.Resources和System.Xml.Linq程序集(ASP.NET Core项目默认已包含)。

二、读取.resx文件内容

用ResXResourceReader读取指定.resx文件的键值对,返回字典格式方便后台展示:

using System.Resources;
using System.IO;

public Dictionary<string, string> ReadResxContent(string resxFilePath)
{
    var resourceDict = new Dictionary<string, string>();
    if (!File.Exists(resxFilePath)) return resourceDict;

    using var reader = new ResXResourceReader(resxFilePath);
    foreach (DictionaryEntry entry in reader)
    {
        if (entry.Key is string key && entry.Value is string value)
        {
            resourceDict[key] = value;
        }
    }
    return resourceDict;
}

三、创建/更新.resx条目

先读取现有内容,覆盖或添加新键值对后,用ResXResourceWriter写入文件:

using System.Resources;
using System.IO;

public void UpsertResxEntry(string resxFilePath, string key, string value)
{
    // 读取现有资源
    var existingResources = new Dictionary<string, string>();
    if (File.Exists(resxFilePath))
    {
        using var reader = new ResXResourceReader(resxFilePath);
        foreach (DictionaryEntry entry in reader)
        {
            if (entry.Key is string existingKey)
            {
                existingResources[existingKey] = entry.Value?.ToString() ?? string.Empty;
            }
        }
    }

    // 更新或添加键值对
    existingResources[key] = value;

    // 写入回文件
    using var writer = new ResXResourceWriter(resxFilePath);
    foreach (var entry in existingResources)
    {
        writer.AddResource(entry.Key, entry.Value);
    }
    writer.Generate();
}

四、删除.resx条目

读取文件时跳过目标键,再重新写入剩余内容:

using System.Resources;
using System.IO;

public void DeleteResxEntry(string resxFilePath, string key)
{
    if (!File.Exists(resxFilePath)) return;

    var remainingResources = new Dictionary<string, string>();
    using var reader = new ResXResourceReader(resxFilePath);
    foreach (DictionaryEntry entry in reader)
    {
        if (entry.Key is string existingKey && existingKey != key)
        {
            remainingResources[existingKey] = entry.Value?.ToString() ?? string.Empty;
        }
    }

    using var writer = new ResXResourceWriter(resxFilePath);
    foreach (var entry in remainingResources)
    {
        writer.AddResource(entry.Key, entry.Value);
    }
    writer.Generate();
}

五、后台页面集成与优化

  1. 权限控制:给资源管理控制器/Action添加[Authorize(Roles = "Admin")]特性,仅允许管理员操作。
  2. 缓存处理:ASP.NET Core默认缓存.resx资源,更新后需清除缓存——可通过IStringLocalizerFactory重新创建本地化实例,或用IMemoryCache存储资源,更新时移除对应缓存键。
  3. 多语言切换:后台提供下拉选择框,支持对不同语言的.resx文件(如Resources.zh-CN.resx、Resources.en-US.resx)进行操作。

六、生产环境更优方案:数据库存储资源

直接操作.resx文件存在并发冲突、版本控制难等问题,建议将多语言资源存到数据库,实现自定义IStringLocalizer从数据库读取:

1. 定义资源实体

public class LocalizationResource
{
    public int Id { get; set; }
    public string Key { get; set; }
    public string Culture { get; set; }
    public string Value { get; set; }
}

2. 实现数据库本地化器

public class DbStringLocalizer : IStringLocalizer
{
    private readonly AppDbContext _dbContext;
    private readonly string _culture;

    public DbStringLocalizer(AppDbContext dbContext, string culture)
    {
        _dbContext = dbContext;
        _culture = culture;
    }

    public LocalizedString this[string name]
    {
        get
        {
            var resource = _dbContext.LocalizationResources
                .FirstOrDefault(r => r.Key == name && r.Culture == _culture);
            var value = resource?.Value ?? name;
            return new LocalizedString(name, value, resource == null);
        }
    }

    public LocalizedString this[string name, params object[] arguments]
    {
        get
        {
            var baseString = this[name];
            return baseString.ResourceNotFound 
                ? baseString 
                : new LocalizedString(name, string.Format(baseString.Value, arguments), false);
        }
    }

    public IEnumerable<LocalizedString> GetAllStrings(bool includeParentCultures)
    {
        var resources = _dbContext.LocalizationResources
            .Where(r => r.Culture == _culture);
        return resources.Select(r => new LocalizedString(r.Key, r.Value));
    }

    public IStringLocalizer WithCulture(CultureInfo culture)
    {
        return new DbStringLocalizer(_dbContext, culture.Name);
    }
}

3. 注册本地化服务

builder.Services.AddDbContext<AppDbContext>(options => 
    options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
builder.Services.AddLocalization();
builder.Services.AddSingleton<IStringLocalizerFactory, DbStringLocalizerFactory>();

这种方案下,后台CRUD直接操作数据库表,比文件操作更稳定灵活,适合生产环境。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 15:55:17