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

查看:380
本文介绍了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

我的ViewModels使用之类的语句

My ViewModels are using statements like

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

这罚款5 MVC只要当过RESX被适当地包括和访问修饰符被设置正确,但它似乎在vNext项目工作
有谁知道如何RESX在MVC 6 vNext项目中使用?

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/6 MVC完成,但我不能找到那里的资源字符串已被用于任何像样的样本。

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.

使用code以上给了我一个错误

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:拿到了本地化位实现穆罕默德的答案后,工作,但我是一个新的错误卡住了。

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();

我得到时得到执行以下code一个新的错误。

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)

如果不能想出一个依赖我丢失或者没有在code一个问题

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

修改3:

要有人还在寻找一个解决方案。在这个时间点上,你可以使用的答案code 穆罕默德热汗SAEE ,以获得本地化支持你CSHTML。然而,对于验证使本地化的故事属性还没有完成(在这个编辑的时间:08 /九月/ 2015)
看一看在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 :

<一个href=\"https://github.com/aspnet/Mvc/issues/2766#issuecomment-137192942\">https://github.com/aspnet/Mvc/issues/2766#issuecomment-137192942

PS:要解决的出现InvalidOperationException我做了以下

PS : To fix the InvalidOperationException I did the following

把所有的依赖关系为beta7- *和清除所有内容
  我的C:\\用户\\ .dnx \\包摆脱了误差

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

这是我提出的问题详细说明:

Details on the issue I raised :

<一个href=\"https://github.com/aspnet/Mvc/issues/2893#issuecomment-127164729\">https://github.com/aspnet/Mvc/issues/2893#issuecomment-127164729

编辑:25 / DEC / 2015年

Edit : 25 / Dec /2015

这是最后在MVC 6现在的工作。

This is finally working in MVC 6 now.

在这里写了一个快速的博客文章:<一href=\"http://pratikvasani.github.io/archive/2015/12/25/MVC-6-localization-how-to/\">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的项目<一个完整的示例href=\"https://github.com/aspnet/Mvc/tree/d06dcbc9962a2a70b92e87e721aa63fb1749d11e/test/WebSites/LocalizationWebSite\"相对=nofollow>此处。在写这个的时候都非常新的code和随时可能更改。您需要将以下添加到您的启动:

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&LT; HomeController的&GT; 继承自 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天全站免登陆