3

I want to set up a route that will match on any url, with a constraint. This is what I have tried:

routes.MapRouteLowercase("CatchAll Content Validation", "{*url}",
    new { controller = "Content", action = "LoadContent" },
    new { url = new ContentURLConstraint(), }
);

and for testing purposes I have the following simple constraint:

public class ContentURLConstraint : IRouteConstraint
{
    public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
    {
        var s = (string)values["url"];
        return s.Contains("comm");              
    }
}

If the constraint is satisfied I when expect to pass the full url to the controll action LoadContent

public ActionResult LoadContent(string url)
{
   return Content(url);
}

I am expecting, when I load a page, for s in the Match function to contain the entire url, so that I can check it, but instead it is null. What might I be missing?

3
  • 1
    Not fully clear what you are trying to achieve. Could you maybe update your question with some examples? Commented May 9, 2017 at 16:05
  • I've added some more detail. In short, I want to check all incoming urls against the constraint, and pass the full url along to the Action if satisfied. The Match function shown is just for illustrating the problem I am having. Commented May 9, 2017 at 16:21
  • Show us what the values object looks like within the method. Commented May 9, 2017 at 16:25

1 Answer 1

2

You get null when there is no url in the route, i.e. host itself: http://localhost:64222.

When there is a url, e.g.: http://localhost:64222/one/two, your url parameter will hold a value: one/two.

You can modify your constraint to something like:

public class ContentURLConstraint : IRouteConstraint
{
    public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values routeDirection)
    {
        var url = values[parameterName] as string;
        if (!string.IsNullOrEmpty(url))
        {
            return url.Contains("comm");
        }

        return false; // or true, depending on what you need.
    }
}

What might I be missing?

Could be that you are missing that url constraint does not contain host, port, schema and query string. If you need it - you can get it from httpContext.Request.

Sign up to request clarification or add additional context in comments.

1 Comment

That makes sense! Thank you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.