我有razor Pages Web应用程序(vs2019,.net core 3.0)。我想本地化网址 “ / fi-fi /联系人” “ / en-US / Contact”
我使用“ DynamicRouteValueTransformer”取得了一些成功,唯一的问题是当我在地址栏输入“ / en-US / Index”时。
public class LanguageTransformer : DynamicRouteValueTransformer
{
public override ValueTask<RouteValueDictionary> TransformAsync(HttpContext httpContext, RouteValueDictionary values)
{
if (!values.ContainsKey("language") || !values.ContainsKey("page"))
return new ValueTask<RouteValueDictionary>(values);
var x = values["page"];
values["page"] = "/" + x;
return new ValueTask<RouteValueDictionary>(values);
}
}
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddLocalization(o =>
{
// We will put our translations in a folder called Resources
o.ResourcesPath = "Resources";
});
services.Configure<RequestLocalizationOptions>(options =>
{
var supportedCultures = new[]
{
new CultureInfo("fi-FI"),
new CultureInfo("en-US"),
};
options.DefaultRequestCulture = new RequestCulture(culture: "fi-FI", uiCulture: "fi-FI");
options.SupportedCultures = supportedCultures;
options.SupportedUICultures = supportedCultures;
});
// get email settings
services.Configure<EmailSettings>(Configuration.GetSection("EmailSettings"));
// PWA
services.AddSingleton(typeof(IHttpContextAccessor), typeof(HttpContextAccessor));
// EMail render service
services.AddScoped<IViewRenderService, ViewRenderService>();
services.AddSingleton<LanguageTransformer>();
services.AddRazorPages()
.AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix)
.AddDataAnnotationsLocalization();
services.AddTransient<IMailService, EMailService>();
//MailKit
services.AddSingleton<IEMailServiceUsingMailKit, EMailServiceUsingMailKit>();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
var locOptions = app.ApplicationServices.GetService<IOptions<RequestLocalizationOptions>>();
app.UseRequestLocalization(locOptions.Value);
//
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapDynamicPageRoute<LanguageTransformer>("{language}/{page}");
endpoints.MapRazorPages();
});
}
}
}
处理请求时发生未处理的异常。
AmbiguousMatchException:该请求匹配了多个端点。匹配项:
/索引 /索引
Microsoft.AspNetCore.Routing.Matching.DefaultEndpointSelector.ReportAmbiguity(CandidateState []候选人状态)