asp.net mvc 中通过url字符串获取controller和action

在项目中遇到需要通过url字符串获取controller和action的情况,百度了 一下找到了一个可以用的方法 ,在这里分享和记录一下

这个方法是在博客园的博问里看到的 原文地址是http://q.cnblogs.com/q/26461/

实现的代码是这样的

string conroller = string.Empty;
string action = string.Empty;
HttpRequest hr = new HttpRequest("", url, "");//这里的url就是要解析的url
TextWriter stringWriter = new StringWriter();
HttpResponse hrs = new HttpResponse(stringWriter);
HttpContext hc = new HttpContext(hr, hrs);
HttpContextWrapper hcw = new HttpContextWrapper(hc);

foreach (Route r in System.Web.Routing.RouteTable.Routes)
{
  RouteData rt = r.GetRouteData(hcw);
  if (rt != null)
  {
    conroller = rt.Values["Controller"].ToString();//解析出来的Controller
    action = rt.Values["Action"].ToString();//解析出来的Action
    break;
  }
} 

使用上面代码要引用两个命名空间

using System.IO;
using System.Web.Routing;

原文中还提到老赵的文章中的方法http://www.cnblogs.com/jeffreyzhao/archive/2009/08/19/use-the-internal-feature.html,这个我没去试过

大家有兴趣的可以自己去看看,弄懂了跟我分享一下

posted @ 2015-11-23 12:13  dotnet007cn  阅读(1712)  评论(0编辑  收藏  举报