首页 > 代码库 > asp.net MVC中获取当前URL/Controller/Action

asp.net MVC中获取当前URL/Controller/Action

一、获取URL(ASP.NET通用):

【1】获取完整url(协议名+域名+虚拟目录名+文件名+参数)

string url=Request.Url.ToString();

【2】获取虚拟目录名+页面名+参数:

string url=Request.RawUrl;(或 string url=Request.Url.PathAndQuery;)

【3】获取虚拟目录名+页面名:

string url=HttpContext.Current.Request.Url.AbsolutePath;(或 string url= HttpContext.Current.Request.Path;)

【4】获取域名:

string url=HttpContext.Current.Request.Url.Host;

【5】获取参数:

string url= HttpContext.Current.Request.Url.Query;

【6】获取端口:

Request.Url.Port


二、获取当前Controller/Action:

RouteData.Route.GetRouteData(this.HttpContext).Values["controller"]RouteData.Route.GetRouteData(this.HttpContext).Values["action"]或RouteData.Values["controller"]RouteData.Values["action"]

在视图中

@ViewContext.RouteData.Route.GetRouteData(this.Context).Values["controller"]@ViewContext.RouteData.Route.GetRouteData(this.Context).Values["action"]或@ViewContext.RouteData.Values["controller"]@ViewContext.RouteData.Values["action"]

很显然上面只能获取当前View的,如果是嵌套的View上面获得的最终的子View的,如果要获取父View的,如下

ControllerContext.ParentActionViewContext.RouteData.Values["controller"]ControllerContext.ParentActionViewContext.RouteData.Values["action"]在视图中@ViewContext.ParentActionViewContext.RouteData.Values["controller"]@CViewContext.ParentActionViewContext.RouteData.Values["action"]

 

参考:

http://stackoverflow.com/questions/4412310/how-to-get-current-controller-and-action-from-inside-child-action

http://blog.itpub.net/28699126/viewspace-1131655/

asp.net MVC中获取当前URL/Controller/Action