微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

asp.net-mvc – MVC 6:如何使用RESX文件?

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

我的viewmodels正在使用如下语句

[required(ErrorMessageResourceType = typeof(Resources.MyProj.Messages),ErrorMessageResourceName = "Fieldrequired")]

只要RESX被正确地包含在访问修饰符中,并且在vNext项目中似乎不起作用
有谁知道如何在MVC 6 vNext项目中使用RESX?

我在GIT中心网站上看到了几个帖子,他们说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:在实现穆罕德的答案后,本地化位工作,但现在我陷入了一个新的错误

一旦我包含

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

包,并在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

编辑:25 / Dec / 2015

现在终于在MVC 6中工作了。

写了一篇快速博客文章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();
    }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


这篇文章主要讲解了“WPF如何实现带筛选功能的DataGrid”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“WPF...
本篇内容介绍了“基于WPF如何实现3D画廊动画效果”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这...
Some samples are below for ASP.Net web form controls:(from http://www.visualize.uk.com/resources/asp
问题描述: 对于未定义为 System.String 的列,唯一有效的值是(引发异常)。 For columns not defined as System.String, the only vali
最近用到了CalendarExtender,结果不知道为什么发生了错位,如图在Google和百度上找了很久,中文的文章里面似乎只提到了如何本地化(就是显示中文的月份)以及怎么解决被下拉框挡住的问题,谈
ASP.NET 2.0 page lifecyle ASP.NET 2.0 event sequence changed a lot since 1.1. Here is the order: App
静态声明: &#39; Style=&quot;position: relative&quot; AppendDataBoundItems=&quot;True&quot;&gt; (无 或 空 或
以下内容是从网络上搜集资料,然后整理而来的。不当之处,请不吝指教。(The following were from network, and edited by myself. Thanks in a
Imports System Imports System.Reflection Namespace DotNetNuke &#39;*********************************
Ok so you have all seen them: “8 million tools for web development”, “5 gagillion tools that if you