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?
You get null
when there is no url
in the route, ie host itself: http://localhost:64222 .
When there is a url, eg: 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
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.