Error messages from ModelState not get localized

2019-06-01 09:39发布

问题:

I am working on an application in mvc4.I want the application to work in English and Russian.I got titles in russian, but error messages are still in english.

My model contains:-

 [Required(ErrorMessageResourceType = typeof(ValidationStrings),
              ErrorMessageResourceName = "CountryNameReq")]            
    public string CountryName { get; set; }

if(ModelState.IsValid) becomes false it will go to GetErrorMessage()

public string GetErrorMessage()
    {  
       CultureInfo ci = new CultureInfo(Session["uiCulture"].ToString());

        System.Threading.Thread.CurrentThread.CurrentUICulture = ci;

        System.Threading.Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(ci.Name);          
    string errorMsg = string.Empty;
    int cnt = 1;
    var errorList = (from item in ModelState
                   where item.Value.Errors.Any()
                   select item.Value.Errors[0].ErrorMessage).ToList();                                                 

        foreach (var item in errorList)
        {
            errorMsg += cnt.ToString() + ". " + item + "</br>";
            cnt++;
        }
        return errorMsg;
    }

But i always get error message in English.How can i customize the code to get current culture.

回答1:

The reason for that is because you are setting the culture too late. You are setting it inside the controller action, but the validation messages were added by the model binder much earlier than your controller action even started to execute. And at that stage the current thread culture was still the default one.

To achieve that you should set the culture much earlier in the execution pipeline. For example you could do that inside the Application_BeginRequest method in your Global.asax

Just like that:

protected void Application_BeginRequest(object sender, EventArgs e)
{
    CultureInfo ci = new CultureInfo(Session["uiCulture"].ToString());
    System.Threading.Thread.CurrentThread.CurrentUICulture = ci;
    System.Threading.Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(ci.Name);
}