您是否在默认路由中指定 id 设置为可选 (UrlParameter.Optional)?
routes.MapRoute(
// route name
"Default",
// url with parameters
"{controller}/{action}/{id}",
// default parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
更新 #1:以下是两种解决方案,一种适用于 id 是查询字符串 (?id={id}),另一种适用于 Uri (/{id}/) 的一部分:
var localPath = Request.Url.LocalPath;
// works with ?id=123
Debug.WriteLine("Request.Url.LocalPath: " + localPath);
// works with /123/
Debug.WriteLine("Remove with LastIndexOf: " + localPath.Remove(localPath.LastIndexOf('/') + 1));
更新 #2:好的,这是另一个尝试。它适用于所有场景(?id=、?id=123、/、/123/)并且我已将操作签名中的Id 更改为int? 而不是int(需要重构) :
var mvcUrlPartsDict = new Dictionary<string, string>();
var routeValues = HttpContext.Request.RequestContext.RouteData.Values;
if (routeValues.ContainsKey("controller"))
{
if (!mvcUrlPartsDict.ContainsKey("controller"))
{
mvcUrlPartsDict.Add("controller", string.IsNullOrEmpty(routeValues["controller"].ToString()) ? string.Empty : routeValues["controller"].ToString());
}
}
if (routeValues.ContainsKey("action"))
{
if (!mvcUrlPartsDict.ContainsKey("action"))
{
mvcUrlPartsDict.Add("action", string.IsNullOrEmpty(routeValues["action"].ToString()) ? string.Empty : routeValues["action"].ToString());
}
}
if (routeValues.ContainsKey("id"))
{
if (!mvcUrlPartsDict.ContainsKey("id"))
{
mvcUrlPartsDict.Add("id", string.IsNullOrEmpty(routeValues["id"].ToString()) ? string.Empty : routeValues["id"].ToString());
}
}
var uri = string.Format("/{0}/{1}/", mvcUrlPartsDict["controller"], mvcUrlPartsDict["action"]);
Debug.WriteLine(uri);