Can i use a route constraint here?

544 Views Asked by At

If i have the following URL:

/someurl

And i have two domain names:

us.foo.com

au.foo.com

I want this to 200 (match):

us.foo.com/someurl

But this to 404 (not match):

au.foo.com/someurl

The route looks like this:

RouteTable.Routes.MapRoute(
   "xyz route",
   "someurl",
   new { controller = "X", action = "Y" }
);

I'm guessing because there are no route values, i can't constraint the URL based on the host? Is that correct?

If so, how can i do this, other than the following (ugly) in the action:

if (cantViewThisUrlInThisDomain)
   return new HttpNotFoundResult();

Anyone got any ideas?

I guess i'm kind of looking for a way to constraint a route via it's domain, not the route token, if that makes sense.

1

There are 1 best solutions below

0
On BEST ANSWER

You could write a custom route:

    public class MyRoute : Route
    {
        public MyRoute(string url, object defaults)
            : base(url, new RouteValueDictionary(defaults), new MvcRouteHandler())
        { }

        public override RouteData GetRouteData(HttpContextBase httpContext)
        {
            var url = httpContext.Request.Url;
            if (!IsAllowedUrl(url))
            {
                return null;
            }
            return base.GetRouteData(httpContext);
        }

        private bool IsAllowedUrl(Uri url)
        {   
            // TODO: parse the url and decide whether you should allow
            // it or not             
            throw new NotImplementedException();
        }
    }

and then register it in the RegisterRoutes method in Global.asax:

routes.Add(
    "xyz route",
    new MyRoute(
        "{someurl}",
        new { controller = "Home", action = "Index" }
    )
);