gpt4 book ai didi

c# - 在所有 Azure Function 调用中强制执行文化不起作用

转载 作者:行者123 更新时间:2023-12-03 03:47:42 30 4
gpt4 key购买 nike

我正在尝试在 Azure 函数中全面实现特定文化(EN-US)

为此,我有一个基类

public class MyFunction
{
protected void EnforceCulture(string culture = Cultures.UK)
{
CultureInfo.CurrentCulture.ClearCachedData();
Thread.CurrentThread.CurrentCulture = new CultureInfo(culture, false);
CultureInfo.CurrentCulture = Thread.CurrentThread.CurrentCulture;
CultureInfo.DefaultThreadCurrentCulture = Thread.CurrentThread.CurrentCulture;
Thread.CurrentThread.CurrentUICulture = Thread.CurrentThread.CurrentCulture;
CultureInfo.CurrentUICulture = Thread.CurrentThread.CurrentUICulture;
CultureInfo.DefaultThreadCurrentUICulture = Thread.CurrentThread.CurrentUICulture;
}

protected async Task<IActionResult> ExecuteWithAuthorization(HttpRequest req, Func<Task<IActionResult>> func)
{
if (req.Unauthorized())
{
return new UnauthorizedResult();
}

//Request is authorized so enforce culture and call logic
EnforceCulture(Cultures.USA);
return await func();
}
}

我按照下面的逻辑在我的函数中使用它

    [FunctionName("my-function")]
[Authorize]
public async Task<IActionResult> MyFunctionAsync(
[HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "my-route")]
HttpRequest req)
{
var response = await ExecuteWithAuthorization(req, async () =>
{
var result = new MyResult()
{
Test = DateTime.Now.ToString("G");
}

var okResult = (IActionResult)new OkObjectResult(result);
return okResult;
});

return response;
}

当我查看 result.Test 时,我希望它将日期显示为美国日期,因为我已强制文化为美国,但它显示为英国

我做错了什么?

我认为问题可能是等待操作在其自己的线程上运行,该线程可能没有从主线程派生的信息(即区域性)。如果是这种情况我该如何解决?

保罗

最佳答案

Azure Functions 不会提供内置方法来更改区域性,需要将以下代码放入 starting of the function

using System.Threading;
using System.Globalization;

//......

string culture = "en-US";
CultureInfo CI = new CultureInfo(culture);
Thread.CurrentThread.CurrentUICulture = CI;

对于 Azure Functions,您可以设置 time zone在应用程序设置中:

WEBSITE_TIME_ZONE=America

对于函数需要使用以下代码创建启动类

[assembly: FunctionsStartup(typeof(Startup))]
namespace FunctionApp
{
public class Startup : IWebJobsStartup
{
public void Configure(IWebJobsBuilder app)
{
var cultureInfo = new CultureInfo("en-US");
CultureInfo.DefaultThreadCurrentCulture = cultureInfo;
CultureInfo.DefaultThreadCurrentUICulture = cultureInfo;
Thread.CurrentThread.CurrentCulture = cultureInfo;
Thread.CurrentThread.CurrentUICulture = cultureInfo;
}
}
}

如需进一步引用,请查看 SO

关于c# - 在所有 Azure Function 调用中强制执行文化不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68497823/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com