It is possible to know in which Routes. Map() the call of an Action fell? ASP.NET MVC5

Asked

Viewed 59 times

2

Afterward of that question I was wondering, is it possible to know on which route map my Action used? Example:

I have two routes.MapRoute()

routes.MapRoute(
    "Home",
    "Image/{id}",
    new
    {
        controller = "Home",
        action = "Image",
        id = UrlParameter.Optional
    },
    new { id = @"\w+" }
);

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

And an Action

 public ActionResult Image(string id)
    {
        Debug.WriteLine(id);
        return View();

    }

Both Map.Route() will work, only in that case would fall on the first option(because both are correct but the one that comes first is used), but if the Map.Route() called "Home" did not work, I would not know in which Map.Route() would be falling when I call Action "Image"

1 answer

2


Yes, you can access route data as your controller inherits Controller or ApiController

public ActionResult Image(string id)
{
    //Caso seja ApiController
    var route = this.ControllerContext.RouteData.Route.RouteTemplate;
    Console.WriteLine(route);

    //Caso seja apenas Controller
    var route = this.ControllerContext.RouteData.Route as Route;
    Console.WriteLine(route.Url);
}

The result in my case is like: "api/{controller}/{action}"

  • 1

    Routetemplate exists?

  • Oops, I already got the answer, Routetemplate only exists in case the inheritance is in Apicontroller.

  • Sure, I searched and saw that the name is not saved :( but anyway already solves the same way ! + 1

Browser other questions tagged

You are not signed in. Login or sign up in order to post.