Search code examples
c#asp.net.nettranslateculture

How to translate C# .NET messages to other cultures?


I am using the entity framework to authenticate and register new users in my system. I would like to know how I can change default return messages from entity as well as from other .NET packages to another culture, for example Spanish.

example output in English from identity:

Username '[email protected]' is already taken.


Solution

  • So directly serving the return from a Database or Framework like Entity Framework isn't safe. As an example, if you directly serve the return of a query, you also share a possible error. And such an error message could contain information that you don't want to share with the end user, like the structure of your db, that can help a potential attacker during a SQL injection.

    In this case, you could create a sort of middleware, like an API endpoint or a Service. Where you first run a query then evaluate the value and decide, what the middleware should return for example that the 'Username '[email protected]' is already taken.'. And between the query and the return of the value, you can perform different tasks like translation and error handling.

    I made here a code example that could maybe help you:

    string CheckIfUserExists(string language, string email)
        if email exists:
            if language == "en":
                reutnr "Sorry email taken"
            if language == "de":
                return "Entschuldigung die Emeil ist vergeben"
    

    A better solution would be to that the server just returns 0 (not taken) or 1 (taken)for example. And the clients make a request to the server and if the return value is 1 the client renders the appropriate message in the correct language.

    I hope this clears up things for you and if you have any questions just reach out to me