首页 > 解决方案 > 在所有 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 时,我希望它将日期显示为美国日期,因为我已将文化强制为美国,但它显示为英国

我究竟做错了什么?

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

保罗

标签: c#azureazure-functions

解决方案


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


推荐阅读