Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 is to get the Controller and Action names from the referring page (i.e. Request.UrlReferrer). Is there an easy way to achieve this?

like image 453
death_au Avatar asked Jan 12 '12 04:01

death_au


People also ask

What is action name and controller name in MVC?

Actions are public methods in an MVC controller, that respond to a URL request. Action Selectors are attributes that can be applied to action methods and are used to influence or control which action method gets invoked in response to a request.


2 Answers

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.

like image 186
gdoron is supporting Monica Avatar answered Oct 08 '22 21:10

gdoron is supporting Monica


To expand on gdoron's answer, the Uri class has methods for grabbing the left and right parts of the URL without having to do string parsing:

url = Request.UrlReferrer.GetLeftPart(UriPartial.Path); querystring = Request.UrlReferrer.Query.Length > 0 ? uri.Query.Substring(1) : string.Empty;  // 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"]; 
like image 31
Joe the Coder Avatar answered Oct 08 '22 20:10

Joe the Coder