How to localize ASP.NET Identity UserName and Password error messages?

Published on Monday, April 16, 2018

Create a custom resource manager

internal class FallbackResourceManager : ResourceManager
{
    private readonly ResourceManager _resourceManager;
    private readonly ResourceManager _fallbackResourceManager;

    public FallbackResourceManager(ResourceManager resourceManager, ResourceManager fallbackResourceManager)
    {
        _resourceManager = resourceManager;
        _fallbackResourceManager = fallbackResourceManager;
    }

    public override string GetString(string name)
    {
        string translation = _resourceManager.GetString(name);
        if (!String.IsNullOrEmpty(translation))
            return translation;
        return _fallbackResourceManager.GetString(name);
    }

    public override string GetString(string name, CultureInfo culture)
    {
        string translation = _resourceManager.GetString(name, culture);
        if (!String.IsNullOrEmpty(translation))
            return translation;
        return _fallbackResourceManager.GetString(name, culture);
    }
}

Replace the default resource manager with the custom resource manager

public static class MicrosoftAspNetIdentityResources
{
    public static void Initialize()
    {
        var resources = Type.GetType("Microsoft.AspNet.Identity.Resources, Microsoft.AspNet.Identity.Core", true);
        var resourceManProperty = resources.GetField("resourceMan", BindingFlags.Static | BindingFlags.NonPublic);
        if(resourceManProperty == null)
            throw new Exception("Failed to retrieve resourceMan property from AspNet identity resources");

        var resourceManager = new ResourceManager("Repo.Core.i18n.Microsoft.AspNet.Identity.Resources", typeof(i18n.Microsoft_AspNet_Identity_Resources).Assembly);
        var microsoftResourceManager = new ResourceManager("Microsoft.AspNet.Identity.Resources", resources.Assembly);
        var resourceMan = new FallbackResourceManager(resourceManager, microsoftResourceManager);
        resourceManProperty.SetValue(null, resourceMan);
    }
}
comments powered by Disqus