Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8578251
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 11, 20262026-06-11T20:20:41+00:00 2026-06-11T20:20:41+00:00

I am having issues getting Web API to work with subdomain-based routes. In short,

  • 0

I am having issues getting Web API to work with subdomain-based routes. In short, I am getting to the right controller and method but the data token out of the subdomain is not being picked up by WebAPI.

I have this in my scenario:

contoso.myapp.com
fabrikam.myapp.com
{tenant}.myapp.com

All resolving to the same ApiController and I want to be able to extract the {tenant} token.

I used the code in this article http://blog.maartenballiauw.be/post/2012/06/18/Domain-based-routing-with-ASPNET-Web-API.aspx

But there is something that seem to have changed between the time the article was written and ASP.NET Web Api went out of beta. The code in the article is relying on RouteTable.Routes while on Web API routes are configured through HttpConfiguration.Routes which is an HttpRouteCollection and not the usual RouteCollection (it derives from RouteCollection actually).

So I changed the code to derive from HttpRoute instead of Route. Here is the code:

https://gist.github.com/3766125

I configure a route like this

 config.Routes.Add(new HttpDomainRoute(
            name: "test",
            domain: "{tenant}.myapp.com",
            routeTemplate: "test",
            defaults: new { controller = "SomeController", action = "Test" }
        ));

And my requests are routed to the right controller. However, the tenant data token is never filled (if I do this.Request.GetRouteData() I see the controller and action tokens but not tenant). If I put a breakpoint on GetRouteData it is never called.

I tried to follow the code path with reflector and see where GetRouteData is being called at the HttpRouteCollection level, but it seems that the collection is enumarating is empty. Not sure exactly how the integration between regular ASP.NET routing and WEb API routing is bridged but it is confusing me.

Any ideas?

The workaround I am using for now is calling explicitly GetRouteData over the Route

this.Request.GetRouteData().Route.GetRouteData(this.Request.RequestUri.ToString(), this.Request)

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-11T20:20:42+00:00Added an answer on June 11, 2026 at 8:20 pm

    After thinking of this more, I have a workaround for you. The basic idea of the workaround is to use a route that derives from Route and add it to the RouteCollection directly. That way, the route we are passing will no longer be wrapped inside HttpWebRoute.

    The RouteByPassing handler is to workaround another known issue. Hope this helps.

    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
    
            RouteTable.Routes.Add("test", new HttpDomainRoute(
                domain: "{tenant}.auth10.com",
                routeTemplate: "test",
                defaults: new { controller = "Values", action = "GetTenant" }
            ));
    
            config.MessageHandlers.Add(new RouteByPassingHandler());
        }
    }
    
    public class RouteByPassingHandler : DelegatingHandler
    {
        protected override System.Threading.Tasks.Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)
        {
            HttpMessageInvoker invoker = new HttpMessageInvoker(new HttpControllerDispatcher(request.GetConfiguration()));
            return invoker.SendAsync(request, cancellationToken);
        }
    }
    
    public class HttpDomainRoute
        : Route
    {
        private Regex domainRegex;
        private Regex pathRegex;
    
        public HttpDomainRoute(string domain, string routeTemplate, object defaults, object constraints = null)
            : base(routeTemplate, new RouteValueDictionary(defaults), new RouteValueDictionary(constraints), new RouteValueDictionary(), HttpControllerRouteHandler.Instance)
        {
            this.Domain = domain;
        }
    
        public string Domain { get; set; }
    
        public override RouteData GetRouteData(HttpContextBase context) 
        {   
            // Build regex
            domainRegex = CreateRegex(this.Domain);
            pathRegex = CreateRegex(this.Url);
    
            // Request information
            string requestDomain = context.Request.Headers["Host"];
            if (!string.IsNullOrEmpty(requestDomain))
            {
                if (requestDomain.IndexOf(":") > 0)
                {
                    requestDomain = requestDomain.Substring(0, requestDomain.IndexOf(":"));
                }
            }
            else
            {
                requestDomain = context.Request.Url.Host;
            }
    
            string requestPath = context.Request.AppRelativeCurrentExecutionFilePath.Substring(2) + context.Request.PathInfo;
    
            // Match domain and route
            Match domainMatch = domainRegex.Match(requestDomain);
            Match pathMatch = pathRegex.Match(requestPath);
    
            // Route data
            RouteData data = null;
            if (domainMatch.Success && pathMatch.Success)
            {
                data = base.GetRouteData(context);
    
                // Add defaults first
                if (Defaults != null)
                {
                    foreach (KeyValuePair<string, object> item in Defaults)
                    {
                        data.Values[item.Key] = item.Value;
                    }
                }
    
                // Iterate matching domain groups
                for (int i = 1; i < domainMatch.Groups.Count; i++)
                {
                    Group group = domainMatch.Groups[i];
                    if (group.Success)
                    {
                        string key = domainRegex.GroupNameFromNumber(i);
    
                        if (!string.IsNullOrEmpty(key) && !char.IsNumber(key, 0))
                        {
                            if (!string.IsNullOrEmpty(group.Value))
                            {
                                data.Values[key] = group.Value;
                            }
                        }
                    }
                }
    
                // Iterate matching path groups
                for (int i = 1; i < pathMatch.Groups.Count; i++)
                {
                    Group group = pathMatch.Groups[i];
                    if (group.Success)
                    {
                        string key = pathRegex.GroupNameFromNumber(i);
    
                        if (!string.IsNullOrEmpty(key) && !char.IsNumber(key, 0))
                        {
                            if (!string.IsNullOrEmpty(group.Value))
                            {
                                data.Values[key] = group.Value;
                            }
                        }
                    }
                }
            }
    
            return data;
        }
    
        public override VirtualPathData GetVirtualPath(RequestContext requestContext, RouteValueDictionary values) 
        {
            return base.GetVirtualPath(requestContext, RemoveDomainTokens(values));
        }
    
        private Regex CreateRegex(string source)
        {
            // Perform replacements
            source = source.Replace("/", @"\/?");
            source = source.Replace(".", @"\.?");
            source = source.Replace("-", @"\-?");
            source = source.Replace("{", @"(?<");
            source = source.Replace("}", @">([a-zA-Z0-9_-]*))");
    
            return new Regex("^" + source + "$");
        }
    
        private RouteValueDictionary RemoveDomainTokens(RouteValueDictionary values)
        {
            Regex tokenRegex = new Regex(@"({[a-zA-Z0-9_-]*})*-?\.?\/?({[a-zA-Z0-9_-]*})*-?\.?\/?({[a-zA-Z0-9_-]*})*-?\.?\/?({[a-zA-Z0-9_-]*})*-?\.?\/?({[a-zA-Z0-9_-]*})*-?\.?\/?({[a-zA-Z0-9_-]*})*-?\.?\/?({[a-zA-Z0-9_-]*})*-?\.?\/?({[a-zA-Z0-9_-]*})*-?\.?\/?({[a-zA-Z0-9_-]*})*-?\.?\/?({[a-zA-Z0-9_-]*})*-?\.?\/?({[a-zA-Z0-9_-]*})*-?\.?\/?({[a-zA-Z0-9_-]*})*-?\.?\/?");
            Match tokenMatch = tokenRegex.Match(Domain);
            for (int i = 0; i < tokenMatch.Groups.Count; i++)
            {
                Group group = tokenMatch.Groups[i];
                if (group.Success)
                {
                    string key = group.Value.Replace("{", "").Replace("}", "");
                    if (values.ContainsKey(key))
                        values.Remove(key);
                }
            }
    
            return values;
        }
    }
    

    }

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I know it can be done but am having issues getting it to work.
I am having some issues getting my JS to work right. I am trying
Im having issues getting this to work, maybe its not even possible? I have
I am having issues getting setCenter to work. My JS console tells me: myMap
I am having issues getting the -e and -d file test operators to work
I'm having some issues getting file uploads to work correctly and the following code
I'm having some issues with getting cookies to work when using a ProxyPass to
I'm having a hell of a time getting WCF Data Services to work within
Having issues getting jQuery to work in this scenario: Visual Studio 2010 .Net 4.0
Having some issues getting this MPMoviePlayerViewController to work. I have two sample URLs pointing

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.