因为https://docs.microsoft.com
,它使用 URL 重定向功能来实现路由https://docs.microsoft.com/aspnet/core/fundamentals/localization?view=aspnetcore-2.2
到https://docs.microsoft.com/en-us/aspnet/core/fundamentals/localization?view=aspnetcore-2.2
. 如果你检查请求日志https://docs.microsoft.com/aspnet
,你会发现第一个请求,它返回响应,Status Code: 301
然后返回https://docs.microsoft.com/en-us/aspnet
。
根据您的要求,如果您只需要localhost:5001/home/index
返回视图localhost:5001/en-us/home/index
而不将 url 更改为localhost:5001/en-us/home/index
. 你可以试试
var localizationOptions = app.ApplicationServices.GetService<IOptions<RequestLocalizationOptions>>().Value;
var requestProvider = new RouteDataRequestCultureProvider();
localizationOptions.RequestCultureProviders.Insert(0, requestProvider);
app.UseRouter(routes =>
{
routes.MapMiddlewareRoute("{culture=en-US}/{*mvcRoute}", subApp =>
{
subApp.UseRequestLocalization(localizationOptions);
subApp.UseMvc(mvcRoutes =>
{
mvcRoutes.MapRoute(
name: "default",
template: "{culture=en-US}/{controller=Home}/{action=Index}/{id?}");
});
});
});
如果您需要与 相同的 URL localhost:5001/en-us/home/index
,您还需要执行重定向操作。
app.Use(async (context, next) =>
{
await next.Invoke();
if (context.Response.StatusCode == StatusCodes.Status404NotFound)
{
context.Response.Redirect(@"/en-us/Home/Index", true);
}
});
app.UseRouter(routes =>
{
routes.MapMiddlewareRoute("{culture}/{*mvcRoute}", subApp =>
{
subApp.UseRequestLocalization(localizationOptions);
subApp.UseMvc(mvcRoutes =>
{
mvcRoutes.MapRoute(
name: "default",
template: "{culture}/{controller=Home}/{action=Index}/{id?}");
});
});
});