【问题标题】:ASP.NET MVC application : could not localize MessageFormat in ApplicationUserManager.RegisterTwoFactorProvider in IdentityConfig.csASP.NET MVC 应用程序:无法在 IdentityConfig.cs 中的 ApplicationUserManager.RegisterTwoFactorProvider 中本地化 MessageFormat
【发布时间】:2024-04-14 07:00:01
【问题描述】:

在具有身份 (2.2.1) 的标准 ASP.NET MVC (5.2.7) 应用程序中,我试图本地化在两因素身份验证期间发送的消息。

我同时拥有PhoneNumberTokenProviderEmailTokenProvider

还有一个项目包含*.resx 文件,其中包含不同语言的文本消息。

在应用程序中,当前语言是根据自定义语言 cookie 设置的。 在每个控制器或视图中,如果我使用Resources.<<message_name>>,我会得到CurrentCulture 的特定消息的文本(Resources 是文本资源项目的类名)。

现在在IdentityConfig.cs 我有:

public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context) 
{
    var manager = new ApplicationUserManager(new UserStore<ApplicationUser>(context.Get<ApplicationDbContext>()));
    ...
    // Register two factor authentication providers. This application uses Phone and Emails as a step of receiving a code for verifying the user
    // You can write your own provider and plug it in here.
    manager.RegisterTwoFactorProvider("Phone Code", new PhoneNumberTokenProvider<ApplicationUser>
            {
                MessageFormat = Resources.MESSAGE_PHONE
            });

每个请求都会调用这个ApplicationUserManager.Create 方法,因此RegisterTwoFactorProvider。问题是Resources.MESSAGE_PHONE 总是返回与服务器语言环境相对应的消息 - 在页面上设置另一种语言时它不会改变。

context 参数具有正确的语言 cookie。

所以问题是为什么IdentityConfig\ApplicationManager.Create 方法Resource.MESSAGE_PHONE 没有以正确的语言返回消息(就像在每个控制器或视图中一样)。项目比较大,可能控制器和视图有一些设置,我忽略了...

如何解决这个问题?

提前致谢!

【问题讨论】:

    标签: c# asp.net-mvc localization asp.net-identity


    【解决方案1】:

    如果你知道去哪里寻找答案就很容易了。

    在我的情况下,CurrentCulture 是在Application_AcquireRequestStateglobal.asax.cs 文件中设置的,它是在IdentityConfig.csApplicationUserManager.Create 方法之后触发的,所以在ApplicationUserManager.CreateCurrentThread 只有默认文化。

    一种解决方案是将设置CurrentThread 文化的代码移动到global.asax.cs 中的Application_BeginRequest 方法中,该方法在IdentityConfig.cs 中的ApplicationUserManager.Create 方法之前触发。

    完整信息here

    【讨论】:

      最近更新 更多