0

For the project I'm working on we have actions performed on things in a location so our url pattern is as follows:

locations/{locationId}/{controller}/{action}/{id}

So we have action signatures like so:

public ActionResult TheAction(long locationId, long id)

Which is good.

My spidey senses want to abstract out the need to include locationId in the action parameter list. Is there a way bind this value into a super class property via a super class or ActionFilter?

1 Answers1

1

The simplest thing to do is to add the locationId route value to each location route.

routes.MapRoute(
    name: "location1",
    url: "location1/{controller}/{action}/{id}",
    defaults: new { locationId = "1", id = UrlParameter.Optional });

routes.MapRoute(
    name: "location2",
    url: "location2/{controller}/{action}/{id}",
    defaults: new { locationId = "2", id = UrlParameter.Optional });

Assuming your locations will include the number, you could use a regex route constraint to make it a bit more dynamic:

routes.MapRoute(
    name: "location",
    url: "location{locationId}/{controller}/{action}/{id}",
    defaults: new { id = UrlParameter.Optional },
    constraints: new { locationId = @"\d+" });

Or you could implement IRouteConstraint to make your locations completely text-based without including the ID, which allows you to map it based on dynamic data.

Another option for database driven data that lets you deal with more than one segment at a time is to create a RouteBase subclass and put your logic there.

Or, you could create .NET Reflection/logic driven routes that are automatically generated and added to the route table, like in this example (but do note that this should only be done at application startup).

Community
  • 1
  • 1
NightOwl888
  • 55,572
  • 24
  • 139
  • 212
  • Unfortunately we have literally thousands of locations so your first suggestion won't scale. AFAICT the links seem overkill just to avoid an extra parameter in the method. But thanks though. – Kevin Pluck Feb 11 '17 at 23:54
  • I updated my answer - I previously overlooked the (much simpler) route constraint, which is ideal for when you only want one dynamic segment. – NightOwl888 Feb 12 '17 at 07:04