是否有人知道如何在网址中隐藏一些参数?
例如,您有一个url参数“culture”。它可以是“en,fr,it”。 默认情况下,您的网站以“en”文化呈现,我们不会在网址中显示默认文化,但在其他文化情况下,参数“文化”必须出现在网址中。
http://myrendersite.net/barbikueue
http://myrendersite.net/fr/barbikueue
这是不同文化中的相同页面。 如何基于默认的asp.net mvc路由系统做什么?
答案 0 :(得分:2)
这会有所帮助:
ASP.NET mvc, localized routes and the default language for the user
Set Culture in an ASP.Net MVC app
您必须注册两条路线:
routes.MapRoute(
name: "DefaultLang",
url: "{language}/{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
constraints: new { language = "[a-z]{2}"}
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
创建一个继承Attribute
的<{1}}:
ActionFilterAttribute
之后使用之前创建的属性创建public class LanguageActionFilterAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var routeDataKey = "language";
var defaultLang = "en";
var defaultCulture = "EN";
// if no language route param received
if (filterContext.RouteData.Values[routeDataKey] == null /* && currentCulture != "en-EN" */)
{
// change culture to en-EN
Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo(string.Format("{0}-{1}", defaultLang, defaultCulture));
Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo(string.Format("{0}-{1}", defaultLang, defaultCulture));
}
else
{
/*if (currentCulture != "whatever")
{
//set culture to whatever
}*/
}
base.OnActionExecuting(filterContext);
}
}
:
BaseController
现在所有[LanguageActionFilter]
public abstract class BaseController : Controller
{
}
都会继承Controllers
,而不是BaseController
答案 1 :(得分:0)
以下RouteConstraint可能有所帮助,
public class CultureConstraint : IRouteConstraint
{
public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values,
RouteDirection routeDirection)
{
if (routeDirection == RouteDirection.UrlGeneration)
{
return values[parameterName] != null &&
(route.Defaults[parameterName] == null ||
values[parameterName].ToString().ToLower() != route.Defaults[parameterName].ToString().ToLower());
}
return true;
}
}
将其用作,
routes.MapRoute(
name: "Culture",
url: "{culture}/{controller}/{action}/{id}",
defaults: new {culture = "en", controller = "Home", action = "Index", id = UrlParameter.Optional},
constraints: new {culture = new CultureConstraint()}
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new {controller = "Home", action = "Index", id = UrlParameter.Optional}
);
此处约束仅适用于出站网址,并且当路线信息中的“文化”等于默认值时,会丢弃候选路线。
我使用了最简单的实现,因为你还没有发布你的路由代码,但这个想法应该有效。
希望这会有所帮助。