How do I get the Controller and Action names from the Referrer Uri?

前端 未结 9 1023
清歌不尽
清歌不尽 2020-12-01 14:06

There\'s a lot of information for building Uris from Controller and Action names, but how can I do this the other way around?

Basically, all I\'m trying to achieve i

9条回答
  •  离开以前
    2020-12-01 14:44

    I think this should do the trick:

    // Split the url to url + query string
    var fullUrl = Request.UrlReferrer.ToString();
    var questionMarkIndex = fullUrl.IndexOf('?');
    string queryString = null;
    string url = fullUrl;
    if (questionMarkIndex != -1) // There is a QueryString
    {    
        url = fullUrl.Substring(0, questionMarkIndex); 
        queryString = fullUrl.Substring(questionMarkIndex + 1);
    }   
    
    // Arranges
    var request = new HttpRequest(null, url, queryString);
    var response = new HttpResponse(new StringWriter());
    var httpContext = new HttpContext(request, response)
    
    var routeData = RouteTable.Routes.GetRouteData(new HttpContextWrapper(httpContext));
    
    // Extract the data    
    var values = routeData.Values;
    var controllerName = values["controller"];
    var actionName = values["action"];
    var areaName = values["area"];
    

    My Visual Studio is currently down so I could not test it, but it should work as expected.

提交回复
热议问题