c# - 在所有 Azure 函数调用中强制执行区域性不起作用
问题描述
我正在尝试在 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 不会提供改变文化的内置方法需要将以下代码放在函数的开头
using System.Threading;
using System.Globalization;
//......
string culture = "en-US";
CultureInfo CI = new CultureInfo(culture);
Thread.CurrentThread.CurrentUICulture = CI;
对于 Azure Functions,您可以在应用设置中设置时区:
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
推荐阅读
- ios - 在 UI 测试 Swift 中处理来自 API 的答案
- jenkins - 如果在该阶段后期确定输入无效,如何重试 groovy 管道中的输入步骤?
- linux - 如何在 Vim 中进行搜索和替换?
- r - 在两个公共列 R 的匹配值上连接两个数据帧
- c# - 从 appsettings.json 读取 List<(string,string[])>
- google-cloud-platform - 撤销 1 个令牌会撤销相同 OAuth 客户端 ID + 用户同意对的所有令牌
- javascript - mapbox gl js,用线连接点
- python - cx_oracle 禁用来自控制台的语句回显
- javascript - 在 react native (js) 中为 python cli 编写 ui
- .net - 如何为 Blazor Web Assembly 实现缓存清除