2013-11-28 44 views
1

我找不到一個通用的方式來從asp.net路由請求中獲取「真正的/未路由的」url。反向查找一個asp.net路由的url

http://www.mysite.com/news/today 

得到:

http://www.mysite.com/news.aspx?date=today 

我的代碼loooks,如:

var currentUrl = HttpContext.Current.Request.Url; 
//if url routing is used 
if (HttpContext.Current.Request.RequestContext.RouteData!=null) 
{ 
    currentUrl = ???    
} 

我試着用GetVirtualPath但有時也與Microsoft.AspNet.FriendlyUrls

返回空值,例如
Request.RequestContext.RouteData.Route.GetVirtualPath(Request.RequestContext,Request.RequestContext.RouteData.Values) 

回答

1

我覺得這個解決方案,似乎在任何情況下工作:

var currentUrl = Request.Url.AbsolutePath; 
if (Page.RouteData != null) 
{ 
    if (Page.RouteData.Route!=null) 
    { 
     var virtualPathData = Page.RouteData.Route.GetVirtualPath(Request.RequestContext, Page.RouteData.Values); 
     if (virtualPathData != null) 
     { 
      //asp.net routing 
      currentUrl = virtualPathData.VirtualPath; 
     } 
     else 
     { 
      //only for Microsoft.AspNet.FriendlyUrls 
      //GetFriendlyUrlFileVirtualPath never returns nulls 
      currentUrl = Request.GetFriendlyUrlFileVirtualPath().Replace("~", ""); 
     } 
    } 
} 

對於查詢字符串使用方法:Request.QueryString