1

I'm experimenting with attribute based routing - it's looking great but I have one problem.

I've scoured the docs (attributerouting.net) and SO, but I can't figure out how to use a custom route constraint and pass in a parameter that includes a forward slash. E.g. a URL.

Attribute on Controller:

    [GET("{url:CustomURLConstraint}")]
    public ActionResult DisplayByURL(string url)
    {
        ...
    }

IRouteConstraint:

public class CustomURLConstraint: IRouteConstraint
{
    public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
    {
        string urlToTest = values[parameterName].ToString();
        ....test for url here...
    }
}

This works great.... except when the URL contains a forward slash, it gives me a 404.

So I added the asterisk to the route parameter, like this:

    [GET("{*url:CustomURLConstraint}")]
    public ActionResult DisplayByURL(string url)
    {
        ...
    }

But now I cannot access the value in the IRouteConstraint class.

In the CustomURLConstraint's Match method, the value of values[parameterName] comes through WITH the catch-all star - as *url.

The route values come through with the action and controller as expected, but with the key url as null. There is no *url key.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Martin Hansen Lennox
  • 2,837
  • 2
  • 23
  • 64

0 Answers0