我的项目已经本地化。我想要的是每当用户更改区域性时,它将用户重定向到他所在的页面。但是现在有了新的区域性。
例如,如果用户在“注册”页面上,则出现的链接是:
http://localhost:49445/pt/Account/Register
以
pt
为文化。我开始环顾四周,想出了这种变革文化方法:
public ActionResult ChangeCulture(string lang)
{
var langCookie = new HttpCookie("lang", lang) { HttpOnly = true };
Response.AppendCookie(langCookie);
string url = this.Request.UrlReferrer.AbsoluteUri;
return Redirect(url);
}
但这显然行不通,因为它将再次将我重定向到
http://localhost:49445/pt/Account/Register
代替
http://localhost:49445/en/Account/Register
我一直到处都找不到任何东西。有人可以指出我正确的方向吗?还是提供一个好的答案?
最佳答案
当前的文化必须成为您的路线的一部分:
Global.asax
const string defaultCulture = "sk";
routes.MapRoute(
"DefaultLocalized",
"{culture}/{controller}/{action}",
new { controller = "Home", action = "Index", culture = defaultCulture },
new { culture = "sk|cz" }
);
为每个请求设置当前的文化:
protected void Application_BeginRequest()
{
SetCurrentCulture();
}
private void SetCurrentCulture()
{
var queryItems = Request.RawUrl.Split(new char [] {'/', '?'}, StringSplitOptions.RemoveEmptyEntries);
var currentCulture = new CultureInfo("sk-SK");
HashSet<string> suportedLanguages = new HashSet<string>() { "sk", "cz" };
var currentLang = string.Empty;
if (queryItems.Length > 0)
currentLang = queryItems[0].ToLowerInvariant();
if (suportedLanguages.Contains(currentLang))
{
if (currentLang == "cz")
{
currentCulture = new CultureInfo("cs-CZ");
}
}
Thread.CurrentThread.CurrentCulture = currentCulture;
Thread.CurrentThread.CurrentUICulture = currentCulture;
}
切换文化的链接:
<a href="@Url.ActionWithCurrentQuery(new { culture = "sk" })" title="Slovensky" class="m-xs right">
<img src="@Url.Content("~/Content/Images/slovak-flag.GIF")" alt="Slovensky" title="Slovensky" />
</a>
当前查询的操作会基于当前url生成html,但具有不同的区域性:
/ en / Home / Action?param = 1变为/ de / Home / Action?param = 1
public static string ActionWithCurrentQuery(this UrlHelper urlHelper, string actionName, string controllerName, object routeValues)
{
var request = urlHelper.RequestContext.HttpContext.Request;
var url = urlHelper.Action(actionName, controllerName, routeValues, "http");
var uriBuilder = new UriBuilder(url);
var query = HttpUtility.ParseQueryString(string.Empty);
foreach (string key in request.QueryString.Keys)
{
query[key] = request[key];
}
var routeQuery = HttpUtility.ParseQueryString(uriBuilder.Query);
foreach (string key in routeQuery)
{
query[key] = routeQuery[key];
}
uriBuilder.Query = query.ToString();
return uriBuilder.ToString();
}
关于c# - ASP.NET MVC 5-使用区域性重定向到同一页面,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/26014121/