MVC 6:如何使用 RESX 文件? [英] MVC 6 : how to use RESX files?

查看:9
本文介绍了MVC 6:如何使用 RESX 文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to migrate my existing ASP.NET MVC 5 project to MVC 6 vNext project , while I have been able to get through and resolve most of the issues , I cant seem to find any documentation on how to use the RESX resource files for localization in MVC 6

我的 ViewModel 正在使用类似

My ViewModels are using statements like

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

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

This worked fine in MVC 5 as long as the RESX was included properly and the access modifiers were set correctly , but it doesnt seem to work in a vNext project Does anyone know how RESX can be used in MVC 6 vNext projects ?

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

I saw a few posts here and on the GIT hub site which say that the localization story for ASP.NET 5 / MVC 6 is complete but I cant find any decent sample where the resource strings have been used.

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

Using the code above gives me a error

错误 CS0246 找不到类型或命名空间名称资源"(您是否缺少 using 指令或程序集引用?)

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 中工作.

Edit : Changed text to clarify that I am looking for implementation of localization in vNext ( MVC 6 )projects , I am able to make it work in MVC 5.

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

Edit 2 : Got the localization bit working after implementing the answer from Mohammed but I am stuck at a new error now.

一旦我包含

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

打包并在 Startup.cs 的 ConfigureServices 中添加以下行

packages and add the following line in ConfigureServices in the Startup.cs

   services.AddMvcLocalization();

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

I get a new error when the following code is getting executed.

  public class HomeController : Controller
    {
        private readonly IHtmlLocalizer _localizer;

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

错误:

处理请求时发生未处理的异常.

An unhandled exception occurred while processing the request.

InvalidOperationException:无法解析服务类型'Microsoft.Framework.Runtime.IApplicationEnvironment' 尝试激活'Microsoft.Framework.Localization.ResourceManagerStringLocalizerFactory'.Microsoft.Framework.DependencyInjection.ServiceLookup.Service.CreateCallSite(ServiceProvider提供者,ISet`1 callSiteChain)

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)

无法确定它是我缺少的依赖还是代码中存在问题

Cant figure out if its a dependency i am missing or there is a issue in the code

编辑 3:

致任何仍在寻找解决方案的人.此时,您可以使用 Muhammad Rehan Saee 的答案中的代码在您的 CSHTML 中获得本地化支持.然而,在验证属性中启用本地化的故事尚未完成(在本次编辑时:2015 年 9 月 8 日)在 GITHUB 网站上查看以下 mvc 的问题:

To anyone still looking for a solution. At this point in time , you can use the code in the answer by Muhammad Rehan Saee to get localization support in your CSHTML. However the story for enabling localization in validation attributes is not yet done( at the time of this edit : 08/Sep/2015) Have a look at the issue on the GITHUB site for mvc below :

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

PS : 为了修复 InvalidOperationException 我做了以下操作

PS : To fix the InvalidOperationException I did the following

以所有依赖为beta7-*并清除所有内容我的 C:Users.dnxpackages 摆脱了错误.

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

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

Details on the issue I raised :

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

2015 年 12 月 25 日

Edit : 25 / Dec /2015

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

This is finally working in MVC 6 now.

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

Wrote a quick blog post here : http://pratikvasani.github.io/archive/2015/12/25/MVC-6-localization-how-to/

推荐答案

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

You can take a look at a full sample on the ASP.NET MVC GitHub project here. At the time of writing this is all very new code and subject to change. You need to add the following into your startup:

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 只是一个名称值对):

The IStringLocalizerFactory seems to be used to create instances of IStringLocalizer from resx types. You can then use the IStringLocalizer to get your localized strings. Here is the full interface (LocalizedString is just a name value pair):

/// <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 继承自 IStringLocalizer):

Finally you can inject the IStringLocalizer into your Controller like so (Note that IHtmlLocalizer<HomeController> inherits from 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:如何使用 RESX 文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆