gpt4 book ai didi

c# - 通过 RequestCultureProviders 处理路由中的文化 (URL)

转载 作者:太空狗 更新时间:2023-10-30 00:23:29 26 4
gpt4 key购买 nike

我想创建一个适当的 requestCultureProviders 来处理 AspNetCore WebApp 中路由的文化,路由模板如下:http//url.domain/{culture}/{controller}/{action}

示例:

我在下面发布了我的第一个脏/草稿解决方案。

最佳答案

Startup.cs

public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
// Add the localization services to the services container
services.AddLocalization(options => options.ResourcesPath = "Resources");

// Add framework services.
services.AddMvc()
// Add support for finding localized views, based on file name suffix, e.g. Index.fr.cshtml
.AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix)
// Add support for localizing strings in data annotations (e.g. validation messages) via the
// IStringLocalizer abstractions.
.AddDataAnnotationsLocalization();

// Configure supported cultures and localization options
services.Configure<RequestLocalizationOptions>(options =>
{
var supportedCultures = new[]
{
new CultureInfo("en"),
new CultureInfo("fr")
};

// State what the default culture for your application is. This will be used if no specific culture
// can be determined for a given request.
options.DefaultRequestCulture = new RequestCulture(culture: "fr", uiCulture: "fr");

// You must explicitly state which cultures your application supports.
// These are the cultures the app supports for formatting numbers, dates, etc.
options.SupportedCultures = supportedCultures;

// These are the cultures the app supports for UI strings, i.e. we have localized resources for.
options.SupportedUICultures = supportedCultures;

// You can change which providers are configured to determine the culture for requests, or even add a custom
// provider with your own logic. The providers will be asked in order to provide a culture for each request,
// and the first to provide a non-null result that is in the configured supported cultures list will be used.
// By default, the following built-in providers are configured:
// - QueryStringRequestCultureProvider, sets culture via "culture" and "ui-culture" query string values, useful for testing
// - CookieRequestCultureProvider, sets culture via "ASPNET_CULTURE" cookie
// - AcceptLanguageHeaderRequestCultureProvider, sets culture via the "Accept-Language" request header
options.RequestCultureProviders.Insert(0, new RouteCultureProvider(options.DefaultRequestCulture));
});
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
var localizationOptions = app.ApplicationServices.GetService<IOptions<RequestLocalizationOptions>>();
app.UseRequestLocalization(localizationOptions.Value);

app.UseMvc(routes =>
{
routes.MapRoute(
name: "InternationalizationDefault",
template: "{culture=en}/{controller=Home}/{action=Index}/{id?}");
});
// ...
}
}

RouteCultureProvider.cs

public class RouteCultureProvider : IRequestCultureProvider
{
private CultureInfo defaultCulture;
private CultureInfo defaultUICulture;

public RouteCultureProvider(RequestCulture requestCulture)
{
this.defaultCulture = requestCulture.Culture;
this.defaultUICulture = requestCulture.UICulture;
}

public Task<ProviderCultureResult> DetermineProviderCultureResult(HttpContext httpContext)
{
//Parsing language from url path, which looks like "/en/home/index"
PathString url = httpContext.Request.Path;

// Test any culture in route
if (url.ToString().Length <= 1)
{
// Set default Culture and default UICulture
return Task.FromResult<ProviderCultureResult>(new ProviderCultureResult(this.defaultCulture.TwoLetterISOLanguageName, this.defaultUICulture.TwoLetterISOLanguageName));
}

var parts = httpContext.Request.Path.Value.Split('/');
var culture = parts[1];

// Test if the culture is properly formatted
if (!Regex.IsMatch(culture, @"^[a-z]{2}(-[A-Z]{2})*$"))
{
// Set default Culture and default UICulture
return Task.FromResult<ProviderCultureResult>(new ProviderCultureResult(this.defaultCulture.TwoLetterISOLanguageName, this.defaultUICulture.TwoLetterISOLanguageName));
}

// Set Culture and UICulture from route culture parameter
return Task.FromResult<ProviderCultureResult>(new ProviderCultureResult(culture, culture));
}
}

添加Resources/Views/View.en.resx 文件使用键/值对 HelloWorld: Hello World !

添加Resources/Views/View.fr.resx文件使用键/值对 HelloWorld: Bonjour tout le monde !

View.cshtml

@using Microsoft.AspNetCore.Mvc.Localization
@inject IViewLocalizer Localizer

<h2>Localizer["HelloWorld"]</h2>

Et Voilà :)

关于c# - 通过 RequestCultureProviders 处理路由中的文化 (URL),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38170739/

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