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
我正在尝试将我现有的ASP.NET MVC 5项目迁移到MVC 6 vNext项目,而我已经能够解决大部分问题,我似乎无法找到有关如何使用RESX资源文件的任何文档MVC中的本地化6
My ViewModels are using statements like
我的ViewModel正在使用类似的语句
[Required(ErrorMessageResourceType = typeof(Resources.MyProj.Messages), ErrorMessageResourceName = "FieldRequired")]
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 ?
只要RESX被正确包含并且访问修饰符设置正确,这在MVC 5中运行良好,但它似乎无法在vNext项目中工作有没有人知道如何在MVC 6 vNext项目中使用RESX?
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.
我在这里和GIT中心网站上看到了一些帖子,它们说ASP.NET 5 / MVC 6的本地化故事已经完成,但我找不到任何使用资源字符串的体面样本。
Using the code above gives me a error
使用上面的代码给我一个错误
Error CS0246 The type or namespace name 'Resources' could not be found (are you missing a using directive or an assembly reference?)
错误CS0246找不到类型或命名空间名称“资源”(您是否缺少using指令或程序集引用?)
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.
编辑:更改文本以阐明我正在寻找vNext(MVC 6)项目中的本地化实现,我能够使其在MVC 5中工作。
Edit 2 : Got the localization bit working after implementing the answer from Mohammed but I am stuck at a new error now.
编辑2:在实施*的答案后得到了本地化位,但我现在陷入了一个新的错误。
Once I Include
一旦我包括在内
"Microsoft.AspNet.Localization": "1.0.0-beta7-10364",
"Microsoft.Framework.Localization": "1.0.0-beta7-10364",
packages and add the following line in ConfigureServices in the Startup.cs
打包并在Startup.cs中的ConfigureServices中添加以下行
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;
}
....
Error :
错误:
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)
InvalidOperationException:尝试激活“Microsoft.Framework.Localization.ResourceManagerStringLocalizerFactory”时,无法解析类型“Microsoft.Framework.Runtime.IApplicationEnvironment”的服务。 Microsoft.Framework.DependencyInjection.ServiceLookup.Service.CreateCallSite(ServiceProvider提供程序,ISet`1 callSiteChain)
Cant figure out if its a dependency i am missing or there is a issue in the code
无法弄清楚我是否缺少依赖关系或代码中存在问题
Edit 3 :
编辑3:
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 :
对于仍在寻找解决方案的人。此时,您可以使用Muhammad Rehan Saee的答案中的代码来获取CSHTML中的本地化支持。但是,在验证属性中启用本地化的故事尚未完成(在编辑时:2015年9月8日)请查看以下mvc的GITHUB站点上的问题:
https://github.com/aspnet/Mvc/issues/2766#issuecomment-137192942
https://github.com/aspnet/Mvc/issues/2766#issuecomment-137192942
PS : To fix the InvalidOperationException I did the following
PS:要修复InvalidOperationException,我执行了以下操作
Taking all dependencies as the beta7-* and clearing all the contents of my C:\Users\.dnx\packages got rid of the error.
将所有依赖项作为beta7- *并清除我的C:\ Users \ .dnx \ packages的所有内容摆脱了错误。
Details on the issue I raised :
我提出的问题的详细信息:
https://github.com/aspnet/Mvc/issues/2893#issuecomment-127164729
https://github.com/aspnet/Mvc/issues/2893#issuecomment-127164729
Edit : 25 / Dec /2015
编辑:25 / Dec / 2015
This is finally working in MVC 6 now.
这终于在MVC 6中工作了。
Wrote a quick blog post here : 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/
2 个解决方案
#1
4
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:
您可以在此处查看ASP.NET MVC GitHub项目的完整示例。在撰写本文时,这是所有非常新的代码,可能会有所变化。您需要在启动中添加以下内容:
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();
}
}
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):
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);
}
Finally you can inject the IStringLocalizer
into your Controller like so (Note that IHtmlLocalizer<HomeController>
inherits from IStringLocalizer
):
最后,您可以将IStringLocalizer注入到Controller中(注意IHtmlLocalizer
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();
}
}
#2
3
Things have been changed in mvc 6.0.0-rc1-final. After going through many other forums, below configuration will work if anyone planning to work with latest changes in localization feature.
mvc 6.0.0-rc1-final中的内容已经发生了变化。经过许多其他论坛后,如果有人计划使用本地化功能的最新更改,则以下配置将起作用。
In startup.cs configure
在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")));
}
and you can start using IHtmlLocalizer in controller.
你可以在控制器中开始使用IHtmlLocalizer。
and you can test with querystring http://localhost:5000/Home/Contact?culture=fr-CH or change the culture in chrome by adding preferred language under "Language and Input Setting"
并且您可以使用查询字符串http:// localhost:5000 / Home / Contact?culture = fr-CH进行测试,或者通过在“语言和输入设置”下添加首选语言来更改chrome中的文化
#1
4
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:
您可以在此处查看ASP.NET MVC GitHub项目的完整示例。在撰写本文时,这是所有非常新的代码,可能会有所变化。您需要在启动中添加以下内容:
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();
}
}
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):
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);
}
Finally you can inject the IStringLocalizer
into your Controller like so (Note that IHtmlLocalizer<HomeController>
inherits from IStringLocalizer
):
最后,您可以将IStringLocalizer注入到Controller中(注意IHtmlLocalizer
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();
}
}
#2
3
Things have been changed in mvc 6.0.0-rc1-final. After going through many other forums, below configuration will work if anyone planning to work with latest changes in localization feature.
mvc 6.0.0-rc1-final中的内容已经发生了变化。经过许多其他论坛后,如果有人计划使用本地化功能的最新更改,则以下配置将起作用。
In startup.cs configure
在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")));
}
and you can start using IHtmlLocalizer in controller.
你可以在控制器中开始使用IHtmlLocalizer。
and you can test with querystring http://localhost:5000/Home/Contact?culture=fr-CH or change the culture in chrome by adding preferred language under "Language and Input Setting"
并且您可以使用查询字符串http:// localhost:5000 / Home / Contact?culture = fr-CH进行测试,或者通过在“语言和输入设置”下添加首选语言来更改chrome中的文化