gpt4 book ai didi

asp.net-core - ASP.NET Core 2.2 中的路由本地化

转载 作者:行者123 更新时间:2023-12-03 18:44:56 25 4
gpt4 key购买 nike

我正在使用 ASP.NET Core 2.2 开发应用程序,我正在努力解决如何实现路由本地化,例如。如果路由中未指定语言,我需要根据请求重定向到路由/en/products。
如果未指定语言,则从 accept-language header 获取语言环境。

最佳答案

下面的演示应用到使用twoLetterLanguageName。引用这个tutorial

1.创建一个RouteDataRequestCultureProvider类(class):

public class RouteDataRequestCultureProvider : RequestCultureProvider
{
public int IndexOfCulture;
public int IndexofUICulture;

public override Task<ProviderCultureResult> DetermineProviderCultureResult(HttpContext httpContext)
{
if (httpContext == null)
throw new ArgumentNullException(nameof(httpContext));

string culture = null;
string uiCulture = null;

var twoLetterCultureName = httpContext.Request.Path.Value.Split('/')[IndexOfCulture]?.ToString();
var twoLetterUICultureName = httpContext.Request.Path.Value.Split('/')[IndexofUICulture]?.ToString();

if (twoLetterCultureName == "de")
culture = "de-DE";
else if (twoLetterCultureName == "en")
culture = uiCulture = "en-US";

if (twoLetterUICultureName == "de")
culture = "de-DE";
else if (twoLetterUICultureName == "en")
culture = uiCulture = "en-US";

if (culture == null && uiCulture == null)
return NullProviderCultureResult;

if (culture != null && uiCulture == null)
uiCulture = culture;

if (culture == null && uiCulture != null)
culture = uiCulture;

var providerResultCulture = new ProviderCultureResult(culture, uiCulture);

return Task.FromResult(providerResultCulture);
}
}

2.还有一个 LanguageRouteConstraint类(class)
public class LanguageRouteConstraint : IRouteConstraint
{
public bool Match(HttpContext httpContext, IRouter route, string routeKey, RouteValueDictionary values, RouteDirection routeDirection)
{

if (!values.ContainsKey("culture"))
return false;

var culture = values["culture"].ToString();
return culture == "en" || culture == "de";
}
}

3.startup.cs ConfigureServices :
services.AddLocalization(options => options.ResourcesPath = "Resources");

services.AddMvc()
.AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix)
.AddDataAnnotationsLocalization();

services.Configure<RequestLocalizationOptions>(options =>
{
var supportedCultures = new List<CultureInfo>
{
new CultureInfo("en"),
new CultureInfo("de"),
};

options.DefaultRequestCulture = new RequestCulture(culture: "en", uiCulture: "en-US");
options.SupportedCultures = supportedCultures;
options.SupportedUICultures = supportedCultures;

options.RequestCultureProviders = new[]{ new RouteDataRequestCultureProvider{
IndexOfCulture=1,
IndexofUICulture=1
}};

});

services.Configure<RouteOptions>(options =>
{
options.ConstraintMap.Add("culture", typeof(LanguageRouteConstraint));
});

4.startup.cs Configure
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
var options = app.ApplicationServices.GetService<IOptions<RequestLocalizationOptions>>();
app.UseRequestLocalization(options.Value);

//other middlewares

app.UseMvc(routes =>
{
routes.MapRoute(
name: "LocalizedDefault",
template: "{culture:culture}/{controller}/{action}/{id?}",
defaults: new {controller = "Home", action = "Index" });
//constraints: new { culture = new CultureConstraint(defaultCulture: "en", pattern: "[a-z]{2}") });

routes.MapRoute(
name: "default",
template: "{controller}/{action}/{id?}",
defaults: new { controller = "Home", action = "Index" });

});
}

然后你可以直接使用 /en/Home/Privacy 在浏览器 url 中更改文化.

If language is not specified then get locale from accept-language header



您可以使用 Url Rewriting Middleware检查路由值并将其重定向到具有默认文化的新路由。

1.创建重定向规则:
public class RewriteRules
{
public static void RedirectRequests(RewriteContext context)
{
//Your logic

var request = context.HttpContext.Request;
var path = request.Path.Value;

var userLangs = request.Headers["Accept-Language"].ToString();
var firstLang = userLangs.Split(',').FirstOrDefault();
var defultCulture = string.IsNullOrEmpty(firstLang) ? "en" : firstLang.Substring(0,2);

//Add your conditions of redirecting
if ((path.Split("/")[1] != "en") && (path.Split("/")[1] != "de"))// If the url does not contain culture
{
context.HttpContext.Response.Redirect($"/{defultCulture}{ request.Path.Value }");
}

}
}

2..在Startup Configure方法中使用中间件:
app.UseAuthentication();//before the Rewriter middleware

app.UseRewriter(new RewriteOptions()
.Add(RewriteRules.RedirectRequests)
);
//MVC middleware

那么如果您输入 /Home/Privacy在浏览器中,它会重定向到 url,如 /en/Home/Privacy .

关于asp.net-core - ASP.NET Core 2.2 中的路由本地化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56280221/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com