, 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);