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

如何在.NET Core 2控制器中使用共享资源实现本地化?

Fixing Shared Localization in .NET Core Controllers

Hey there! I get where you're coming from—switching from WebForms to .NET Core already has a learning curve, and localization can feel tricky when the view side works but controllers don't. Let's walk through getting shared resource localization up and running in your controllers step by step.

First, Double-Check Your Base Configuration

Before diving into controllers, make sure your shared resource setup is fully configured (since you got views working, this might already be done, but it's worth verifying):

  1. Create a Shared Resource Class
    Add an empty class (no properties needed) to your project—name it something like SharedResources.cs (you can put it in the root or a Resources folder). This acts as the "anchor" for your localized resource files.

  2. Register Localization Services
    In your Program.cs (or Startup.cs if you're on an older .NET Core version), make sure you've registered shared localization along with view/data annotation localization:

    // Set up resource path (adjust if your resources are in a different folder)
    builder.Services.AddLocalization(options => options.ResourcesPath = "Resources");
    
    builder.Services.AddControllersWithViews()
        // Keep your existing view localization setup
        .AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix)
        // Tie data annotations to shared resources (optional but useful)
        .AddDataAnnotationsLocalization(options =>
        {
            options.DataAnnotationLocalizerProvider = (type, factory) =>
                factory.Create(typeof(SharedResources));
        })
        // Add shared localization support
        .AddSharedLocalization(options => options.ResourcesPath = "Resources");
    
    // Configure supported cultures and request localization middleware
    var supportedCultures = new[] { "en-US", "zh-CN" }; // Add your target cultures
    var localizationOptions = new RequestLocalizationOptions()
        .SetDefaultCulture(supportedCultures[0])
        .AddSupportedCultures(supportedCultures)
        .AddSupportedUICultures(supportedCultures);
    
    // Important: This middleware needs to run before routing
    app.UseRequestLocalization(localizationOptions);
    
  3. Verify Resource Files
    Ensure your resource files are named correctly and set to embed in the assembly:

    • For English: SharedResources.resx
    • For Chinese (Simplified): SharedResources.zh-CN.resx
    • Place them in the Resources folder (or match the path you set in ResourcesPath)
    • In each resource file's properties, set Build Action to Embedded Resource

Inject and Use Shared Localization in Controllers

Now for the controller part—this is where the magic happens:

  1. Inject the Shared Localizer
    Add ISharedStringLocalizer<SharedResources> to your controller's constructor. This is the key service for accessing shared resources in controllers:

    using Microsoft.Extensions.Localization;
    
    public class HomeController : Controller
    {
        private readonly ISharedStringLocalizer<SharedResources> _sharedLocalizer;
    
        // Inject the shared localizer via constructor
        public HomeController(ISharedStringLocalizer<SharedResources> sharedLocalizer)
        {
            _sharedLocalizer = sharedLocalizer;
        }
    }
    
  2. Use Localized Strings in Actions
    Now you can pull localized text directly in your action methods, whether you're passing it to a view, returning it in an API response, or using it for validation messages:

    public IActionResult Index()
    {
        // Get a localized string from your shared resources
        var welcomeMessage = _sharedLocalizer["WelcomeMessage"];
        
        // Pass it to the view (like you might have done in WebForms)
        ViewBag.Welcome = welcomeMessage;
        
        // Or if it's an API controller, return it directly
        // return Ok(new { Message = welcomeMessage });
    
        return View();
    }
    

Troubleshooting Common Issues

If it's still not working, check these common pitfalls:

  • Wrong Localizer Type: Don't use IStringLocalizer<T> where T is your controller—use ISharedStringLocalizer<SharedResources> to target the shared resource files.
  • Resource File Naming: Make sure the resource files match the name of your SharedResources class exactly (case-sensitive on some OSes).
  • Middleware Order: UseRequestLocalization must come before UseRouting and UseEndpoints—otherwise, the culture won't be set when your controller runs.
  • Embedded Resource Setting: If your resource files aren't set to Embedded Resource, the app won't find them at runtime.

Give these steps a shot, and if you hit a specific error (like a missing resource exception), feel free to share details—I can help narrow it down further!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 04:21:07