ASP.NET WebApi中异步调用的本地化

时间:2012-12-31 08:46:26

标签: asp.net asynchronous asp.net-web-api

嗨 - 我计划基于“Accept-Language”标头处理错误字符串等服务器端本地化,通过基于该标头设置CurrentUICulture,但显然它不会通过异步调用流动,下面是一个示例代码来说明问题,是否有任何默认的方法来处理异步调用的本地化?

   public async Task<HttpResponseMessage> GetAsync()
    {            
        //set the current ui culture, to say "fr-FR", based on "Accept-Language" header
        Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("**fr-FR**");  

       var task = httpClient.PutAsync(endpoint, content)            

        //do some processing

        var res  = await task;

        var culture = Thread.CurrentThread.CurrentUICulture.Name; **//ITS NOT necessarily fr-FR**

        //do some more processing
        //and handle localizations etc.

        return res;
    }

我正在寻找一种更清晰/无缝的方式来处理本地化,尤其是存在真正的异步操作的情况。对于await调用之后的代码

编辑:为了清晰起见,用httpClient.PutAsync替换了Task.Run()

1 个答案:

答案 0 :(得分:2)

Task.RunTask.Factory.StartNew没有任何背景信息。这是一种预期的行为。使用await关键字时会保留上下文。所以这就是你能做的:

public static async Task<IEnumerable<string>> GetAsync()
{            
    //set the current ui culture, to say "fr-FR", based on "Accept-Language" header
    Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("fr-FR");

    //do some processing

    var s = await GetSomething();

    var culture = Thread.CurrentThread.CurrentUICulture.Name; //It's ja-JP

    return new[] { s, s };
}

public static Task<string> GetSomething()
{
    var cuture = Thread.CurrentThread.CurrentUICulture.Name; // It's fr-FR
    var tcs = new TaskCompletionSource<string>();
    Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("ja-JP");
    tcs.SetResult("<something>");
    return tcs.Task;
}