Application unhandled exceptions localization

后端 未结 2 410
孤城傲影
孤城傲影 2021-01-24 08:42

I am trying to display error messages in locale language and for all handled exceptions my team is using resource file to display in local language but Is there a way to interce

2条回答
  •  佛祖请我去吃肉
    2021-01-24 09:25

    Standard .NET exceptions are localized and message language will depend on current thread culture. So for you to make it work you'll need to implement RequestCultureMiddleware that would change the language based on your needs. Here is an example:

    public class RequestCultureMiddleware
    {
        private readonly RequestDelegate next;
    
        public RequestCultureMiddleware(RequestDelegate next)
        {
            this.next = next;
        }
    
        public async Task Invoke(HttpContext context)
        {
            // Get it from HTTP context as needed
            var language = "fr-FR";
    
            var culture = new System.Globalization.CultureInfo(language);
            System.Threading.Thread.CurrentThread.CurrentCulture = culture;
            await next(context);
        }
    }
    

    Register it before MVC in Startup class:

    app.UseMiddleware(typeof(RequestCultureMiddleware));
    app.UseMvc();
    

    Please note: displaying exception message is not covered here.

提交回复
热议问题