Reputation: 87
Let's say my urls are:
https://www.mywebsite.com/app/company/employees/5
https://www.mywebsite.com/app/company/employees?id=5&name=jack
https://www.mywebsite.com/app/company/employees/5?clockId=1
I'm looking for a way to get the "base" path, or whatever it's called. Like the "base" path would be "/app/company/employees" for all, without the "/5" part or "?id=5&name=jack" or "/5?clockId=1" parts.
I was using string.Join("/", context.Request.ApplicationPath, context.Request.RequestContext.RouteData.Values["controller"], context.Request.RequestContext.RouteData.Values["action"])
to get it (context is HttpContext), but it doesn't work the way I want since it includes the Index action too. Like if the Url is "https://www.mywebsite.com/app/company" I want "/app/company/" not "/app/company/Index". I can always check if the action is Index or not but it feels like kind of a "code smell" to me.
Also using context.Request.Url.AbsolutePath
doesn't work either since it returns "/app/company/employees/5" (It returns the path with Id)
Upvotes: 0
Views: 1628
Reputation: 8156
Looks like the only two things you need from URL are action
and controller
and if the action is "index" you don't need it. In this case I believe that you are doing it right. This is a slightly modified piece of code I was using in ASP.NET MVC
project:
string actionName = this.ControllerContext.RouteData.Values["action"].ToString();
string controllerName = this.ControllerContext.RouteData.Values["controller"].ToString();
if (actionName.Equals("index", StringComparison.InvariantCultureIgnoreCase))
{
actionName = string.Empty;
}
string result = $"/{controllerName}/{actionName}";
There is one more thing to mention: "areas". Once I was working on website which had them, so they may appear in your URL too if your website uses "area" approach.
I hope it helps 😊
Upvotes: 1