0

I am new to .NET Core 6 and I have realized that several things should be done manually.

One of them is localization. For example, when using a simple action to change the user password, the message "Incorrect password." is returned in the errors collection when the old password mismatch.

I have spent a lot of time trying to localize that simple message so that it is shown in Spanish. I have read a lot of pages telling about this but none works. I think it is because this message is not a DataAnnotation message.

When I used .NET Framework, all of these were made automatically since the resource DLL is always installed by default. It seems that in .NET Core 6 those DLL's are missing, or at least, they are vey hidden.

As an attempt, I added this to Program.cs file:

builder.Services.AddMvc()
    .AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix, options => options.ResourcesPath = "Resources")
    .AddDataAnnotationsLocalization();

builder.Services.AddLocalization(options => options.ResourcesPath = "Resources");

builder.Services.Configure<RequestLocalizationOptions>(options =>
{
    var supportedCultures = new[] { new CultureInfo("en"), new CultureInfo("es") };
    options.DefaultRequestCulture = new RequestCulture("es");
    options.SupportedCultures = supportedCultures;
    options.SupportedUICultures = supportedCultures;
});

app.UseRequestLocalization();

And also added a file "Resouces\ErrorMessages.es.resx" with an entry whose key is PasswordMismatch with the message in Spanish, but no avail.

Any help, please?

jstuardo
  • 3,901
  • 14
  • 61
  • 136
  • There are different types of error messages and each require special setup. This nuget will simplify all localization setup [XLocalizer](https://docs.ziyad.info/en/XLocalizer/v1.0/index.md), and if you are interested to do everything manually you can read [this](http://www.ziyad.info/en/articles/10-Developing_Multicultural_Web_Application) article and the [docs](https://learn.microsoft.com/en-us/aspnet/core/fundamentals/localization?view=aspnetcore-6.0). – LazZiya Nov 07 '22 at 05:49
  • @LazZiya I am not interested to do that stuff manually. I expected the system do that by the developer. For example, when creating a new user and password does not meet complexity requirements, this error is returned: "Passwords must have at least one non alphanumeric character.". When I used .NET Framework, that message appeared correctly in Spanish. This is not happening in .NET Core 6 and as I understand, XLocalizer is for localizing custom texts. I need to localize system messages because doing that manually is crazy. – jstuardo Nov 07 '22 at 22:46
  • Actually XLocalizer is to localize all texts and system error messages (model binding, identity errors and data annotations), it also do online translation for missing localizations and inserts the localized text into the resource file automatically. – LazZiya Nov 08 '22 at 06:51

2 Answers2

0

Alought I couldn't check the details of your resourcefile,I think there's something wrong with your resourcefile for the name you've shown

Resouces\ErrorMessages.es.resx

I tried in my case as below:

enter image description here

enter image description here

public class TestModel
    {
        
        [Required(ErrorMessage = "The Email field is required.")]
        [EmailAddress(ErrorMessage = "The Email field is not a valid email address.")]
        [Display(Name = "Email")]
        public string Email { get; set; }

        [Required(ErrorMessage = "The Password field is required.")]
        [StringLength(8, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
        [DataType(DataType.Password)]
        [Display(Name = "Password")]
        public string Password { get; set; }

        [DataType(DataType.Password)]
        [Display(Name = "Confirm password")]
        [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
        public string ConfirmPassword { get; set; }
    }

in Razor View:

<div class="row">
    <div class="col-md-4">
        <form asp-action="Create">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            <div class="form-group">
                <label asp-for="Email" class="control-label"></label>
                <input asp-for="Email" class="form-control" />
                <span asp-validation-for="Email" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Password" class="control-label"></label>
                <input asp-for="Password" class="form-control" />
                <span asp-validation-for="Password" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="ConfirmPassword" class="control-label"></label>
                <input asp-for="ConfirmPassword" class="form-control" />
                <span asp-validation-for="ConfirmPassword" class="text-danger"></span>
            </div>
            <div class="form-group">
                <input type="submit" value="Create" class="btn btn-primary" />
            </div>
        </form>
    </div>
</div>

It works well:

enter image description here

Update:

Since You are not interested in developing a multilingual site,I think the most simlpe solution is Custom an Attribute as below:

public class CusRequiredAttribute: RequiredAttribute
    {
        public CusRequiredAttribute()
        {
            //You could wrote the errormessage in your language as well
            ErrorMessage = "{0}Required";
        }
    }

add [CusRequired]attrbute on the target property

for developing a multilingual site

Create an empty class named SharedResources and a resource file as below:

enter image description here

enter image description here

set as below in startup:

services.AddControllersWithViews()
                .AddDataAnnotationsLocalization(
                options =>
                {
                    options.DataAnnotationLocalizerProvider = (type, factory) =>
                        factory.Create(typeof(SharedResources));
                });

Result:

enter image description here

Ruikai Feng
  • 6,823
  • 1
  • 2
  • 11
  • Yes, but it means I need to add `ErrorMessage` property in the models. In such a case, I could use directly the message in Spanish because I am not interested in developing a multilingual site. When I worked with .NET Framework, all default messages appeared correctly in Spanish without needing to add `ErrorMessage` in the models. Since messages such as `field is required` are default messages, I wonder why .NET Core did not added messages in other languages, for example, as a separate Nuget Package. In .NET Framework there was files similar to this: System.Web.Mvc.resources.dll – jstuardo Nov 09 '22 at 11:40
  • I've updated my answer,please check it – Ruikai Feng Nov 10 '22 at 07:16
  • Hello again...I am facing a problem that I haven't found a way to solve using `ErrorMessage` property. If a property in the model is defined as `int` but I enter a string, this message appears: "The value 'fsfsf' is not valid for MyProperty.". How can I translate that kind of messages where there is no equivalent attribute? I was trying with `DataType` attribute but it seems it is not the attribute to do that. Maybe I should create a custom attribute also to check for integer? I wouldn't think so since that validation is already part of the language. – jstuardo Nov 15 '22 at 20:27
0

A hint: if the problem is with the PasswordValidator (it wasn't getting the translated messages from the resource file), you can do it (in .NET 7, at least):

var passwordValidator = new PasswordValidator<ApplicationUser>(new LocalizedIdentityErrorDescriber());

And the LocalizedIdentityErrorDescriber is defined here: https://stackoverflow.com/a/53587825/1673326

If anyone needs the pt-BR translated messages, here they are: https://drive.google.com/file/d/1lNu6YjsGvJto4_fCg6MtdIE6vZrldKkC/view?usp=sharing

paulodrjr
  • 41
  • 4