Application unhandled exceptions localization

青春壹個敷衍的年華 提交于 2019-12-02 06:42:05

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.

Near the start of our app we have a line of code that looks similar to

    config.Services.Replace(typeof(IExceptionHandler), new UnhandledExceptionHandler());

and this seems to catch errors.

We also have a catch-all route at the end of our route tables that looks a bit like

        config.Routes.MapHttpRoute(
            name: "NotImplemented",
            routeTemplate: "{*data}",
            defaults: new { controller = "Error", action = "notimplemented", data = UrlParameter.Optional });

where we call the same code. You can check the Accept-Language header to make your best guess at what locale your caller might be able to use. Re-post a specific question if you need help with that aspect.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!