1

I am try to get the url of the website plus the current controller without the method that called it.

Inside the ExampleController, ExampleMethod Request.Url.ToString()

=>http://localhost:51747/.../ExampleController/ExampleMethod

I need

http://localhost:51747/.../ExampleController

The solution I would use is to parse and remove everything after the last slash, but I am not sure if there is already a method to do this using the server info.

Satbir Kira
  • 792
  • 6
  • 21
  • [Possible duplicate question?](http://stackoverflow.com/q/18248547/636942) – Brad C Jun 10 '15 at 13:53
  • Just to get you started, if you have access to the Url helper I would look into the `RouteData` rather than treating the url as a string.. – Octopoid Jun 10 '15 at 13:56
  • Need to generate a string that is emailed. – Satbir Kira Jun 10 '15 at 13:58
  • You can use the `RouteData` to find the controller, action, id and anything else you may have defined in your Route rules. Then you can recreate a string in whatever form you want. Of course, if you're not worried about extra data in the route, querystring, url hash codes etc, you can just strip the last section as you suggested. – Octopoid Jun 10 '15 at 14:00
  • [When I needed to generate a URL for an email I did this](http://stackoverflow.com/a/2005404/636942) – Brad C Jun 10 '15 at 14:01
  • I may be mistaken, but I think the question is looking for how to get the CURRENT url, sans action, rather than just generate a url from a known controller and action. The first answer in the first link that @br4d posted tells you how to use the RouteData to get what you need. – Octopoid Jun 10 '15 at 14:02

1 Answers1

0

Your issue can be solved by using one of the Url.Action HTML helper overloads. To generate your example URL:

http://localhost:51747/.../ExampleController

You would need to do:

@Url.Action("ExampleController", "Index", null, Request.Url.Scheme)

assuming you are using the default ASP.NET MVC Routing config.

In more detail, if the action you provide to the helper is one set as a default in the routeconfig, then it not be specified in the resulting URL.

routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}/{id}",
    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);

See the action = "Index" default? Whatever you have set there is what you will have to use when generating the URL.

Brad C
  • 2,868
  • 22
  • 33
  • As per the first comment from @br4d, you can use: `string controllerName = this.ControllerContext.RouteData.Values["controller"].ToString();` To get the current controller name as you requested. – Octopoid Jun 10 '15 at 14:08