【发布时间】:2016-03-29 14:04:31
【问题描述】:
谁能解释一下虚拟路径是如何计算的? 根据 RouteData.Values 还是根据 url 模式?
我正在尝试删除一些路由数据值,但虚拟路径仍然没有改变。 我有一个问题,虚拟路径在 URL 的开头返回带有冗余斜杠,例如:/he/controller/action 文化之前的斜杠是多余的......
我正在使用如下自定义路由
routes.Add("Default",
new CustomRoute("{culture}/{controller}/{action}/{id}",
new
{
controller = "Desktop",
action = "Index",
culture = "he-IL",
guid = "",
id = UrlParameter.Optional
}));
routes.Add("Wizard_" + wizard,
new CustomRoute("{guid}/{culture}/" + wizardName + "/{action}/{id}",
new
{
controller = wizard,
action = "Index",
culture = "he-IL",
guid = "",
id = UrlParameter.Optional
}));
问题是当使用 Url.Action(action, controller) 方法并且动作在向导控制器中时,所以动作的 URL 是向导格式,如 {guid}/{culture}/" + wizard + "/ {action}/{id} bu guid 值为空,返回的 URL 为 //he-il/controller/action 而不是 /he-il/controller/action
CustomRoute 类:
public class CustomRoute : Route
{
private List<string> _wizards;
public CustomRoute(string uri, object defaults)
: base(uri, new RouteValueDictionary(defaults), new MvcRouteHandler())
{
_wizards = new List<string>();
FillWizards(ref _wizards);
DataTokens = new RouteValueDictionary();
}
public override RouteData GetRouteData(HttpContextBase httpContext)
{
bool hasGuid = httpContext.Request.RequestContext.RouteData != null
&& httpContext.Request.RequestContext.RouteData.Values != null
&& httpContext.Request.RequestContext.RouteData.Values.ContainsKey("guid")
&& !httpContext.Request.RequestContext.RouteData.Values["guid"].ToString().Equals(Guid.Empty);
var routeData = base.GetRouteData(httpContext);
if (routeData == null)
return null;
bool isWizard = _wizards.Contains(routeData.Values["controller"].ToString());
Debug.WriteLine("Controller: " + routeData.Values["controller"] + " action: " + routeData.Values["action"] + " Is wizard: " + isWizard + " has guid: " + hasGuid);
if (isWizard && !hasGuid)
{
if (string.IsNullOrEmpty(routeData.Values["guid"].ToString()))
{
routeData.Values["guid"] = Guid.NewGuid().ToString("N");
}
}
return routeData;
}
public override VirtualPathData GetVirtualPath(RequestContext requestContext, RouteValueDictionary values)
{
VirtualPathData path;
path = base.GetVirtualPath(requestContext, values);
return path;
}
private void FillWizards(ref List<string> items)
{
var _configuration = ObjectFactory.GetInstance<IConfiguration>();
List<string> wizards = _configuration.GetParamValue<string>("SessionUniqueWizards", "").Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToList();
items = wizards;
}
}
【问题讨论】:
-
请发布您的路由配置。您是否使用
MapRoute扩展方法?您是否使用自定义路线?从技术上讲,GetVirtualPath可以使用自定义路由返回您想要的任何内容,因此请展示您的代码。 -
好的,我正在更新我的问题
-
请发布您的
CustomRoute课程的代码。
标签: asp.net-mvc asp.net-mvc-routing