gpt4 book ai didi

c# - ASP.NET MVC、本地化路由和用户的默认语言

转载 作者:可可西里 更新时间:2023-11-01 08:39:01 25 4
gpt4 key购买 nike

我正在使用 ASP.NET MVC 本地化路由。因此,当用户访问英文站点时,它是 example.com/en/Controller/Action,而瑞典站点是 example.com/sv/Controller/Action

我如何确保当用户进入网站时他/她直接进入正确的语言?我知道如何获得我想要的语言,这不是问题。我曾经做的事情是,我将这种文化放入 RegisterRoutes 方法中。但是因为我的页面处于集成模式,所以我无法从 Application_Start 获取请求。

那么我应该如何确保路线从一开始就是正确的呢?

最佳答案

我就是这样做的。

~~免责声明:伪代码~~

global.asax

public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.IgnoreRoute("{*favicon}",
new { favicon = @"(.*/)?favicon.ico(/.*)?" });

routes.MapRoute(
"Question-Answer", // Route name
"{languageCode}/{controller}/{action}", // URL with parameters
new {controller = "home", action = "index"} // Parameter defaults
);

}

请注意: Controller 和/或操作不需要是第一个和第二个。事实上,它们根本不需要存在于 url with parameters 部分。

然后……

HomeController.cs

public ActionResult Index(string languageCode)
{
if (string.IsNullOrEmpty(languageCode) ||
languageCode != a valid language code)
{
// No code was provided OR we didn't receive a valid code
// which you can't handle... so send them to a 404 page.
// return ResourceNotFound View ...
}

// .. do whatever in here ..
}

奖金建议

您还可以添加 Route Constraint到您的路线,因此它只接受 languageCode 参数的某些字符串。 So stealing this dude's code ....

(更多伪代码)...

public class FromValuesListConstraint : IRouteConstraint
{
public FromValuesListConstraint(params string[] values)
{
this._values = values;
}

private string[] _values;

public bool Match(HttpContextBase httpContext,
Route route,
string parameterName,
RouteValueDictionary values,
RouteDirection routeDirection)
{
// Get the value called "parameterName" from the
// RouteValueDictionary called "value"
string value = values[parameterName].ToString();

// Return true is the list of allowed values contains
// this value.
return _values.Contains(value);
}
}

意味着你可以这样做......

routes.MapRoute(
"Question-Answer", // Route name
"{languageCode}/{controller}/{action}", // URL with parameters
new {controller = "home", action = "index"} // Parameter defaults
new { languageCode = new FromValuesListConstraint("en", "sv", .. etc) }
);

好了 :)

我为我的 MVC Api 版本控制做了类似的事情。

GL :) 希望这对您有所帮助。

关于c# - ASP.NET MVC、本地化路由和用户的默认语言,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3683404/

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