Question

Is it possible to add constraints to a custom route inheriting from RouteBase?

My route looks something like this:

public class PageRoute : RouteBase {

public override RouteData GetRouteData(HttpContextBase httpContext)
{
    var path = httpContext.Request.Path;
    if (path.Contains("api") || path.Contains("ui"))
    {
        return null;
    }

I think this this looks a bit shady and I would like to register my route and say, if the url contains api or ui don't even bother to try this route. Is this possible?

Was it helpful?

Solution

A few notes: 1. You want to derive from Route and not RouteBase if you want to just specify constraints. Constraints are introduced in the Route class. 2. There is nothing wrong with specifying the constraints like you have (explicitly in GetRouteData) it's just not extensible. 3. The path.Containts("api") is not a very good constraints and similarly not the one with "ui", it will fail for several reasons (case insensitivity and strings like "maping" will fail it).

So you want to consider something like:

var segments = path.Split(new[] { '/' });
segments.Any(segment => segment.Equals("api", StringComparison.OrdinalIgnoreCase) ||
             segment.Equals("ui", StringComparison.OrdinalIgnoreCase));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top