简体   繁体   中英

Change culture for HttpResponse messages and exceptions in Asp.Net

I'm trying to have all error messages and reponses in an ASP.Net application in the english language. This is what I tried (at the beginning of the Configure method):

        CultureInfo.CurrentCulture = CultureInfo.CreateSpecificCulture("en-US");
        CultureInfo.CurrentUICulture = CultureInfo.CurrentCulture;
        CultureInfo.DefaultThreadCurrentCulture = CultureInfo.CurrentCulture;
        CultureInfo.DefaultThreadCurrentUICulture = CultureInfo.CurrentCulture;
        System.Threading.Thread.CurrentThread.CurrentCulture = CultureInfo.CurrentCulture;
        System.Threading.Thread.CurrentThread.CurrentUICulture = CultureInfo.CurrentCulture;

        var supportedCultures = new[] { "en-US" };
        var localizationOptions = new RequestLocalizationOptions()
            .SetDefaultCulture(supportedCultures[0])
            .AddSupportedCultures(supportedCultures)
            .AddSupportedUICultures(supportedCultures);
        localizationOptions.DefaultRequestCulture = new RequestCulture(supportedCultures[0]);

        app.UseRequestLocalization(localizationOptions);

Here is the exception message that I get back (I'm using Flulrl, but using HttpClient gives same results):

resp = await _flurlClient
                .Request("Accounts", "Login")
                .PostJsonAsync(loginModel);

Call failed. Impossibile stabilire la connessione. Rifiuto persistente del computer di destinazione. (localhost:5001)...

I tried hosting both on Kestrel and IIS Express, nothing changes. What am I missing?

You're missing 2 part:

  • Add the services.AddLocalization(); , this will register IStringLocalizerFactory and the generic IStringLocalizer for you
  • app.UseRequestLocalization make use of the IOptions<RequestLocalizationOptions> , which you're currently missing too.

So the code should be:

// Registering things
services.AddLocalization();

var supportedCultures = new[]
    {
        new CultureInfo("en-US")
    };

services.Configure<RequestLocalizationOptions>(opts =>
    {
        opts.DefaultRequestCulture = new RequestCulture("en-US");
        opts.SupportedCultures = supportedCultures;
        opts.SupportedUICultures = supportedCultures;

        opts.AddInitialRequestCultureProvider(new CustomRequestCultureProvider(context =>
        Task.FromResult(new ProviderCultureResult("en-US"))));
    });

// Using things
app.UseRequestLocalization();

Note: As you want to only return english localization as example, I just made the config to set "en-US" would be your only choice. If you need true localization, use your own logic at var supportedCultures and opts.AddInitialRequestCultureProvider

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM