项目添加App_GlobalResources文件夹
文件夹下添加资源文件
Language.resx //为中文资源文件
Language.en-US.resx
新建CultureHandler类
public class CultureHandler: DelegatingHandler { private List<string> supportedCulture = new List<string>() { "zh-CN", "en-US" }; protected override System.Threading.Tasks.Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) { HttpHeaderValueCollection<StringWithQualityHeaderValue> acceptedLanguage = request.Headers.AcceptLanguage; if (acceptedLanguage != null && acceptedLanguage.Count > 0) { StringWithQualityHeaderValue preferredLanguage = acceptedLanguage.OrderByDescending(e => e.Quality ?? 1.0D) .Where(e => !e.Quality.HasValue || e.Quality.Value > 0.0D) .FirstOrDefault( e => supportedCulture.Contains(e.Value, StringComparer.OrdinalIgnoreCase)); if (preferredLanguage != null) { Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo(preferredLanguage.Value); // 如需要,此处也可同时设置CurrentCulture属性 Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo(preferredLanguage.Value); } if (acceptedLanguage.Any(e => e.Value == "*" && (!e.Quality.HasValue || e.Quality.Value > 0.0D))) { string selectedCulture = supportedCulture.FirstOrDefault(e => !acceptedLanguage.Any( ee => ee.Value.Equals(e, StringComparison.OrdinalIgnoreCase) && ee.Quality.HasValue && ee.Quality.Value == 0.0D)); if (!string.IsNullOrWhiteSpace(selectedCulture)) { Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo(preferredLanguage.Value); // 如需要,此处也可同时设置CurrentCulture属性 Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo(selectedCulture); } } } return base.SendAsync(request, cancellationToken); } }
WebApiConfig
config.MessageHandlers.Add(new CultureHandler());
引用resource资源文件
Resources.Language.User_name_or_password_wrong
为了调试,我们使用Fiddler来进行,运行项目之后,我们通过设置HTTP请求头信息中的Accept-Lanuage,可以得到不同语言的响应。