我正在进行.NET Core Web API本地化,已经完成了所有配置,但是无法获取本地特定值。
任何人都可以建议并告诉我是否错过了配置中的任何内容。
中间件
namespace i18n
{
using System.Globalization;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
/// <summary>
/// The LocalizationMiddleware class.
/// </summary>
public class LocalizationMiddleware
{
private readonly RequestDelegate _next;
/// <summary>
/// Initializes a new instance of the <see cref="LocalizationMiddleware"/> class.
/// </summary>
/// <param name="next">The next.</param>
public LocalizationMiddleware(RequestDelegate next)
{
_next = next;
}
/// <summary>
/// Invokes the specified context.
/// </summary>
/// <param name="context">The context.</param>
/// <returns>Task.</returns>
public async Task Invoke(HttpContext context)
{
var localValue = "en-US";
if (context.Request.Query.ContainsKey("locale"))
{
localValue = context.Request.Query["locale"];
}
Thread.CurrentThread.CurrentCulture = new CultureInfo(localValue);
Thread.CurrentThread.CurrentUICulture = new CultureInfo(localValue);
await _next.Invoke(context);
}
}
/// <summary>
/// The LocalizationMiddlewareExtensions class.
/// </summary>
public static class LocalizationMiddlewareExtensions
{
/// <summary>
/// Uses the localization middleware.
/// </summary>
/// <param name="builder">The builder.</param>
/// <returns>The ApplicationBuilder.</returns>
public static IApplicationBuilder UseLocalizationMiddleware(this IApplicationBuilder builder)
{
return builder.UseMiddleware<LocalizationMiddleware>();
}
} }
启动课程
我已经注册了中间件。
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseLocalizationMiddleware();
}
Web API控制器
[HttpGet]
public ActionResult<IEnumerable<string>> Get()
{
var name = Employees.Name; // Always Name is coming english value
return new string[] { name };
}
这是我的解决方案结构: