如何在.NET Core 2控制器中使用共享资源实现本地化?
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):
Create a Shared Resource Class
Add an empty class (no properties needed) to your project—name it something likeSharedResources.cs(you can put it in the root or aResourcesfolder). This acts as the "anchor" for your localized resource files.Register Localization Services
In yourProgram.cs(orStartup.csif 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);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
Resourcesfolder (or match the path you set inResourcesPath) - In each resource file's properties, set Build Action to
Embedded Resource
- For English:
Inject and Use Shared Localization in Controllers
Now for the controller part—this is where the magic happens:
Inject the Shared Localizer
AddISharedStringLocalizer<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; } }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>whereTis your controller—useISharedStringLocalizer<SharedResources>to target the shared resource files. - Resource File Naming: Make sure the resource files match the name of your
SharedResourcesclass exactly (case-sensitive on some OSes). - Middleware Order:
UseRequestLocalizationmust come beforeUseRoutingandUseEndpoints—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

