MVC 6:如何使用 RESX 文件?

MVC 6 : how to use RESX files?

我正在尝试将我现有的 ASP.NET MVC 5 项目迁移到 MVC 6 vNext 项目,虽然我已经能够解决并解决大部分问题,但我似乎无法找到任何文档说明如何在 MVC 6 中使用 RESX 资源文件进行本地化

我的 ViewModel 正在使用类似

的语句
 [Required(ErrorMessageResourceType = typeof(Resources.MyProj.Messages), ErrorMessageResourceName = "FieldRequired")]

只要正确包含 RESX 并正确设置访问修饰符,这在 MVC 5 中工作正常,但它似乎在 vNext 项目中不起作用 有谁知道如何在 MVC 6 vNext 项目中使用 RESX?

我在这里和 GIT 中心网站上看到一些 post 说 ASP.NET 5 / MVC 6 的本地化故事已经完成,但我找不到合适的使用资源字符串的示例。

使用上面的代码给我一个错误

Error CS0246 The type or namespace name 'Resources' could not be found (are you missing a using directive or an assembly reference?)

编辑:更改文本以阐明我正在寻找 vNext (MVC 6) 项目中的本地化实现,我能够使其在 MVC 5 中工作。

编辑 2:在实施 Mohammed 的回答后本地化位开始工作,但我现在遇到了一个新错误。

一旦我包含

  "Microsoft.AspNet.Localization": "1.0.0-beta7-10364",
    "Microsoft.Framework.Localization": "1.0.0-beta7-10364",

packages 并在 Startup.cs

的 ConfigureServices 中添加以下行
   services.AddMvcLocalization();

执行以下代码时出现新错误。

  public class HomeController : Controller
    {
        private readonly IHtmlLocalizer _localizer;

        public HomeController(IHtmlLocalizer<HomeController> localizer)
        {
            _localizer = localizer;
        }
          ....

错误:

An unhandled exception occurred while processing the request.

InvalidOperationException: Unable to resolve service for type 'Microsoft.Framework.Runtime.IApplicationEnvironment' while attempting to activate 'Microsoft.Framework.Localization.ResourceManagerStringLocalizerFactory'. Microsoft.Framework.DependencyInjection.ServiceLookup.Service.CreateCallSite(ServiceProvider provider, ISet`1 callSiteChain)

无法弄清楚它是否是我缺少的依赖项或代码中存在问题

编辑 3 :

对于仍在寻找解决方案的任何人。此时,您可以使用 Muhammad Rehan Saee 的答案中的代码在您的 CSHTML 中获得本地化支持。然而,在验证属性中启用本地化的故事尚未完成(在编辑时:08/Sep/2015) 查看下面 mvc 的 GITHUB 站点上的问题:

https://github.com/aspnet/Mvc/issues/2766#issuecomment-137192942

PS:为了修复 InvalidOperationException,我执行了以下操作

Taking all dependencies as the beta7-* and clearing all the contents of my C:\Users\.dnx\packages got rid of the error.

关于我提出的问题的详细信息:

https://github.com/aspnet/Mvc/issues/2893#issuecomment-127164729

编辑:2015 年 12 月 25 日

现在终于可以在 MVC 6 中使用了。

在这里写了一篇简短的博客 post:http://pratikvasani.github.io/archive/2015/12/25/MVC-6-localization-how-to/

您可以查看 ASP.NET MVC GitHub 项目 here 上的完整示例。在撰写本文时,这些都是非常新的代码,可能会发生变化。您需要将以下内容添加到您的启动中:

public class Startup
{
    // Set up application services
    public void ConfigureServices(IServiceCollection services)
    {
        // Add MVC services to the services container
        services.AddMvc();
        services.AddMvcLocalization();

        // Adding TestStringLocalizerFactory since ResourceStringLocalizerFactory uses ResourceManager. DNX does
        // not support getting non-enu resources from ResourceManager yet.
        services.AddSingleton<IStringLocalizerFactory, TestStringLocalizerFactory>();
    }

    public void Configure(IApplicationBuilder app)
    {
        app.UseCultureReplacer();

        app.UseRequestLocalization();

        // Add MVC to the request pipeline
        app.UseMvcWithDefaultRoute();
    }
}

IStringLocalizerFactory 似乎用于从 resx 类型创建 IStringLocalizer 的实例。然后您可以使用 IStringLocalizer 来获取您的本地化字符串。这是完整的接口(LocalizedString只是一个名称值对):

/// <summary>
/// Represents a service that provides localized strings.
/// </summary>
public interface IStringLocalizer
{
    /// <summary>
    /// Gets the string resource with the given name.
    /// </summary>
    /// <param name="name">The name of the string resource.</param>
    /// <returns>The string resource as a <see cref="LocalizedString"/>.</returns>
    LocalizedString this[string name] { get; }

    /// <summary>
    /// Gets the string resource with the given name and formatted with the supplied arguments.
    /// </summary>
    /// <param name="name">The name of the string resource.</param>
    /// <param name="arguments">The values to format the string with.</param>
    /// <returns>The formatted string resource as a <see cref="LocalizedString"/>.</returns>
    LocalizedString this[string name, params object[] arguments] { get; }

    /// <summary>
    /// Gets all string resources.
    /// </summary>
    /// <param name="includeAncestorCultures">
    /// A <see cref="System.Boolean"/> indicating whether to include
    /// strings from ancestor cultures.
    /// </param>
    /// <returns>The strings.</returns>
    IEnumerable<LocalizedString> GetAllStrings(bool includeAncestorCultures);

    /// <summary>
    /// Creates a new <see cref="ResourceManagerStringLocalizer"/> for a specific <see cref="CultureInfo"/>.
    /// </summary>
    /// <param name="culture">The <see cref="CultureInfo"/> to use.</param>
    /// <returns>A culture-specific <see cref="IStringLocalizer"/>.</returns>
    IStringLocalizer WithCulture(CultureInfo culture);
}

最后你可以像这样将 IStringLocalizer 注入到你的控制器中(注意 IHtmlLocalizer<HomeController> 继承自 IStringLocalizer):

public class HomeController : Controller
{
    private readonly IHtmlLocalizer _localizer;

    public HomeController(IHtmlLocalizer<HomeController> localizer)
    {
        _localizer = localizer;
    }

    public IActionResult Index()
    {
        return View();
    }

    public IActionResult Locpage()
    {
        ViewData["Message"] = _localizer["Learn More"];
        return View();
    }
}

mvc 6.0.0-rc1-final 中的内容已更改。在浏览了许多其他论坛后,如果有人计划使用本地化功能的最新更改,则以下配置将起作用。

在startup.cs配置

public void ConfigureServices(IServiceCollection services)
    {           
        services.AddMvc();           
        services.AddMvc().AddViewLocalization().AddDataAnnotationsLocalization();
        services.AddSingleton<IStringLocalizerFactory, CustomStringLocalizerFactory>();
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {           
        var requestLocalizationOptions = new RequestLocalizationOptions
        {                
            SupportedCultures = new List<CultureInfo>{
                new CultureInfo("en-US"),    
                new CultureInfo("fr-CH")
            },
            SupportedUICultures = new List<CultureInfo>
            {
                new CultureInfo("en-US"),                    
                new CultureInfo("fr-CH")                    
            }
        };
        app.UseRequestLocalization(requestLocalizationOptions, new RequestCulture(new CultureInfo("en-US")));           
    }

您可以开始在控制器中使用 IHtmlLocalizer。

并且您可以使用查询字符串 http://localhost:5000/Home/Contact?culture=fr-CH 进行测试,或者通过在 "Language and Input Setting"

下添加首选语言来更改 chrome 中的区域性