Search code examples
asp.net-mvcasp.net-mvc-routing

MVC Routing - wildcard URL, but constrained


I basically want to do this:

routes.MapRoute(
  "Pass-through",
  "/api/{*url}",
  new { controller = "PassThrough", action = "PassThroughToApi" });

and the controller I am directing the request to has:

public ContentResult PassThroughToApi(string url = null)

However, I want to be able at the same time to constraint the URL. Such as:

routes.MapRoute(
  "Pass-through",
  "/api/v1/some/specific/address/{whatever}/{parameters}",
  new { controller = "PassThrough", action = "PassThroughToApi" });

But I still want the Controller to get the requested URL as a variable and I don't care about getting the actual parameters, as long as the URL matches the pattern. Or should I just get the requested URL from another place, like a context, instead of being passed to it as a parameter?


Solution

  • You can create custom route constraint

    public class ApiRedirectingConstraint : IRouteConstraint
    {
        private string _matchUrl;
    
        public ApiRedirectingConstraint(string matchUrl)
        {
            _matchUrl = matchUrl;
        }
    
        public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
        {
            string url = (string)values["url"];
    
            bool isMatch = true;
            //check url for specific match with _matchUrl
    
            return isMatch;
        }
    }
    

    and assign it to the Pass-through route

    routes.MapRoute(
        "Pass-through",
        "/api/{*url}",
        new { controller = "PassThrough", action = "PassThroughToApi" },
        new { apiRedirect = new ApiRedirectingConstraint("/api/v1/some/specific/address/{whatever}/{parameters}") }
    );