LoginSignup
1
2

More than 5 years have passed since last update.

[ASP .NET MVC 5] ValidationメッセージLocaleを変えたい/多言語化

Posted at

基本

Resourceファイルを言語ごとに分けたい場合、ResourceをCultureInfoごとに作っておき、CurrentCulture の設定で切り替えればよい。

Resources
├─ Messages.en.resx
└─ Messages.resx

CultureInfo culture = CultureInfo.CreateSpecificCulture("en");
Thread.CurrentThread.CurrentCulture = culture;
Thread.CurrentThread.CurrentUICulture = culture;

よくある間違い

ActionFilterに上記処理を記述し、リクエストによってメッセージの切替をする。
通常のRazor(CSHTML)のメッセージの切替は正常に動作するが、ActionFilterより前に実行されるModelValidationのメッセージは切り替えられない。

    public class LangActionAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            //言語設定
            string lang = AuthorizationUtil.GetAuthData()?.Lang ?? Const.DEFAULT_LANG;
            Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(lang);
            System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo(lang);
            return base.BeginExecute(requestContext, callback, state);
        }
    }

対応

ModelValidationよりも前で実施する。


    public abstract class BaseController : Controller
    {
        protected override IAsyncResult BeginExecute(RequestContext requestContext, AsyncCallback callback, object state)
        {
            //言語設定
            string lang = AuthorizationUtil.GetAuthData()?.Lang ?? Const.DEFAULT_LANG;
            Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(lang);
            System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo(lang);
            return base.BeginExecute(requestContext, callback, state);
        }
    }

参考:
https://afana.me/archive/2011/01/14/aspnet-mvc-internationalization.aspx/
https://stackoverflow.com/questions/24060184/how-to-set-culture-as-globally-in-mvc5

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2