如何修改 Blazor(服务器)中的当前文化日期格式? [英] How to modify the current culture date format in Blazor (server)?

查看:28
本文介绍了如何修改 Blazor(服务器)中的当前文化日期格式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

ASP.NET Core Blazor 全球化和本地化声明:

Blazor 的 @bind 功能会根据用户的当前文化执行格式并解析值以进行显示.
可以从 System.Globalization.CultureInfo.CurrentCulture 属性 访问当前文化.

Blazor's @bind functionality performs formats and parses values for display based on the user's current culture.
The current culture can be accessed from the System.Globalization.CultureInfo.CurrentCulture property.

这句话是对的,但问题是,文化必须在使用之前(或者可能每次刷新 DOM 时)设置.

The statement is true, but the problem is that, the culture has to be set just before it is used (or maybe each time the DOM is refreshed).

为了演示,我将使用标准的 blazor 计数器应用程序.让我们修改Counter.razor

For demonstration I will use standard blazor counter application. Let's modify Counter.razor

@page "/counter"
@using System.Globalization;

<h1>Counter</h1>
<input type="text" @bind="currentDate" />

<p>Current count: @currentCount</p>

<button class="btn btn-primary" @onclick="IncrementCount">Click me</button>

@code {
    private DateTime currentDate = DateTime.Now;
    private int currentCount = 0;

    private void IncrementCount() {
        if (currentCount < 2) Utils.SetCCDateFormat();
        currentCount++;
    }

    public class Utils {
        public static void SetCCDateFormat() {
            var cc = CultureInfo.CurrentCulture.Clone() as CultureInfo;
            cc.DateTimeFormat.ShortDatePattern = "dd-yyyy-m";
            CultureInfo.CurrentCulture = cc;
            CultureInfo.CurrentUICulture = cc;
        }
    }

} 

结果是:

  • 当页面第一次呈现时,文本框包含格式化的日期按服务器默认文化.
  • 第一次和第二次按下按钮时,日期格式为 dd-yyyy-m

我试图修改 OnAfterRenderOnInitialized 中的日期但没有成功.我发现,唯一可用的解决方案是在剃刀标记的乞求上设置格式.

I attempted to modify the date in OnAfterRender, OnInitialized without success. Only usable solution, I have found, is setting the format on the begging of razor markup.

@{Utils.SetCCDateFormat();}

有没有办法修改 CurrentCulture 使其在 blazor 电路中持久化?

观察到的行为是正确的还是错误?

Is the observed behavior correct or is it a bug?

编辑

到目前为止我发现了什么

可以在创建 blazor 端点之前在中间件中设置区域性属性 (CultureInfo.CurrentCulture),并且更改在电路生命周期内是持久的.当我们在组件生命周期方法中修改 CurrentCulture 时,更改只是暂时的(直到方法结束).

It is possible to set culture properties (CultureInfo.CurrentCulture) in a middleware before the blazor endpoint is created and the changes are persistent for the circuit lifetime. When we modify CurrentCulture in component lifecycle methods the change is only temporary (till the end of the method).

我对这个问题的理解是

  • 创建电路后,它会将当前文化存储在某处
  • 服务器的线程数有限
  • 需要时将线程分配给电路,当前区域性由开头存储的内容设置
  • 可以修改CurrentCulture,但这不会影响设置存储,因此当调用另一个事件方法(其他线程)时,将使用原始文化.
  • When a circuit is created it stores the current culture somewhere
  • A server has a limited number of threads
  • A thread is assigned to a circuit when required and the current culture is set by what was stored at the beginning
  • It is possible to modify the CurrentCulture, but this doesn't influence the setting storage and so when another event method is called (other thread) the original culture is used.

所以问题似乎是:如何在电路文化设置已经创建的情况下修改它?

也许这是不可能的,有必要进行完全刷新(再次启动带有导航的请求)并使用中间件来设置修改后的区域性.文化储存存在只是我的猜想,我没有任何参考支持.

Maybe it is not possible and it is necessary do full refresh (start a request again with navigation) and use a middleware to set a modified culture. A culture storage existence is only my conjecture and I don't have any reference to support it.

非常感谢 Tyeth 和 Ashquzzaman 的帮助,但我不会将他们的尝试作为答案.

Many thanks to Tyeth and Ashiquzzaman for help but I am not taking their attempts as the answer.

推荐答案

1) 使用 中间件

示例:

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
      //your Code
        app.Use(async (context, next) =>
        {
            var culture = CultureInfo.CurrentCulture.Clone() as CultureInfo;// Set user culture here
            culture.DateTimeFormat.ShortDatePattern = "dd-yyyy-m";
            CultureInfo.CurrentCulture = culture;
            CultureInfo.CurrentUICulture = culture;

            // Call the next delegate/middleware in the pipeline
            await next();
        });
      //your Code
    }

2) 带有服务的自定义中间件:

2) Custom middleware with service:

服务:

public interface ICultureService
{
    void SetCCDateFormat();
}
public class CultureService : ICultureService
{
    public void SetCCDateFormat()
    {
        CultureInfo culture = (CultureInfo)CultureInfo.CurrentCulture.Clone();
        culture.DateTimeFormat.ShortDatePattern = "dd-yyyy-m";
        CultureInfo.CurrentCulture = culture;
        CultureInfo.CurrentUICulture = culture;
    }
}

中间件:

public class CultureMiddleware
{
    private readonly RequestDelegate _next;

    public CultureMiddleware(RequestDelegate next)
    {
        _next = next;

    }

    public Task Invoke(HttpContext context, ICultureService culture)
    {           
        culture.SetCCDateFormat();
        return this._next(context);
    }
}

启动:

    public void ConfigureServices(IServiceCollection services)
    {
        //Your Code
        services.AddScoped<ICultureService, CultureService>();
        //Your Code
    }
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        //Your Code
        app.UseMiddleware<CultureMiddleware>();
        //Your Code
    }

Culture.razor:

@page "/culture"
@inject ICultureService CultureService
<h1>Counter</h1>
<input type="text" @bind="currentDate" />

<p>Current count: @currentCount</p>

<button class="btn btn-primary" @onclick="IncrementCount">Click me</button>

@code {
    private DateTime currentDate = DateTime.Now;
    private int currentCount = 0;

    private void IncrementCount()
    {
         if (currentCount < 2) CultureService.SetCCDateFormat();
        currentCount++;
    }
}

3) 如果您可以更改应用程序的默认文化,请使用 本地化中间件.Blazor 服务器应用程序将本地化中间件用于 本地化全球化.请求的当前文化设置在 本地化中间件.本地化中间件在 Startup.Configure 方法中启用.本地化中间件必须在任何可能检查请求文化的中间件之前配置(例如,app.UseMvcWithDefaultRoute()).

3) If you can to change default Culture of the application the use localization Middleware. Blazor Server apps are using Localization Middleware for Localization & Globalization. The current culture on a request is set in the localization Middleware. The localization middleware is enabled in the Startup.Configure method. The localization middleware must be configured before any middleware which might check the request culture (for example, app.UseMvcWithDefaultRoute()).

示例:

var culture = new CultureInfo("en-US");
            culture.DateTimeFormat.ShortDatePattern = "dd-yyyy-MM";
            var supportedCultures = new List<CultureInfo> { culture };
        app.UseRequestLocalization(new RequestLocalizationOptions
        {
            DefaultRequestCulture = new RequestCulture(culture, culture),
            // Formatting numbers, dates, etc.
            SupportedCultures = supportedCultures,
            // UI strings that we have localized.
            SupportedUICultures = supportedCultures
        });

这篇关于如何修改 Blazor(服务器)中的当前文化日期格式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆