ASP.NET Routing - Capture Entire URL with Restriction

I want to customize route

that will fit anyone url

, with a limitation. This is what I 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 met, I expect to pass the full url to the controll LoadContent action

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

      

I expect when I load the page for in a function to contain the whole so that I can check it, but this is instead . What can I lose? s

Match

url

null

+3


source to share


1 answer


You get null

when there is no in the route url

, that is, the host itself is: http: // localhost: 64222 .

When there is a URL-address, for example: http: // localhost: 64222 / one's / to two two , your option url

will contain the value: one/two

.

You can change your limit 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 can I lose?

What you are probably missing is that the URL constraint does not contain host, port, schema, and query string. If you need it, you can get it from httpContext.Request

.

+2


source







All Articles