本地化的ASP.NET的WebAPI异步调用 [英] Localization for async calls in ASP.NET WebApi

查看:566
本文介绍了本地化的ASP.NET的WebAPI异步调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,我正打算以处理服务器端的本地化错误字符串等。接受语言头,通过设置基于标头的CurrentUICulture,但显然它不流动虽然异步调用,下面是一个示例code来说明这个问题,有没有处理的国产化,为异步调用任何默认方式?

Hi– I'm planning to handle server side localization for error strings etc. based on the "Accept-Language" header, by setting the CurrentUICulture based on that header, but apparently it doesn’t flow though the async calls, below is a sample code to illustrate the problem, is there any default way of handling the localization for async calls?

   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;
    }

我在寻找处理对那里有真正的异步操作ESP的情况下定位的清洁剂/无缝的方式。为code以下的调用的await

I'm looking for a cleaner/seamless way of handling localization for cases where there are real async operations esp. for the code following the await call

编辑:更换Task.Run()与httpClient.PutAsync为清楚起见

replaced Task.Run() with httpClient.PutAsync for clarity

推荐答案

Task.Run Task.Factory.StartNew 没有任何背景。这是一个预期的行为。 Context是preserved当您使用的await 关键字。因此,这里是你可以做什么:

Task.Run and Task.Factory.StartNew do not have any context. That's an expected behavior. Context is preserved when you use the await keyword. So here's what you could do:

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;
}

这篇关于本地化的ASP.NET的WebAPI异步调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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