开发者

Is it possible to get the controller, action and routeValues from a URL (based on the Global.asax routes)?

I have a URL. Is it possible to somehow get the controller- and action-name and the routevalues? 开发者_Python百科(which would normally be generated by the .NET MVC framework based on the definition in global.asax)


Where and when do you want to get the values?

From within your code you can call:

HttpContextBase context = new HttpContextWrapper(HttpContext.Current);
RouteData rd = RouteTable.Routes.GetRouteData(context);

if (rd != null) {
    string controllerName = rd.GetRequiredString("controller");
    string actionName = rd.GetRequiredString("action");
}

Please note that this only works from within your application's code. There is definitely no way to get this information about other sites and applications.


It is possible, check Haacked routing debugger.


You can get current controller name and Action name by adding Application_BeginRequest method inside your Global.asaxcs file.

Here is an example:

    protected void Application_BeginRequest(object sender, EventArgs args)
    {
        HttpContextBase currentContext = new HttpContextWrapper(HttpContext.Current);

        UrlHelper urlHelper = new UrlHelper(HttpContext.Current.Request.RequestContext);
        RouteData routeData = urlHelper.RouteCollection.GetRouteData(currentContext);

        string url = currentContext.Request.Url.AbsoluteUri;
        string httpMethod = currentContext.Request.HttpMethod;   
        string action = routeData.Values["action"] as string;
        string controller = routeData.Values["controller"] as string;

        if (!string.IsNullOrEmpty(controller) && !string.IsNullOrEmpty(action))
        {
           Logger.Log( controller, action, url, httpMethod);
        }
    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜