13

I'm following the example here for a self-hosted ASP.NET Web API service. However, when specifying "localhost" as the host in the base address, it is translated to "+" (meaning "all available").

var baseAddress = new Uri("http://localhost:13210");
var configuration = new HttpSelfHostConfiguration(baseAddress);
configuration.Routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "{controller}/{id}",
    defaults: new {id = RouteParameter.Optional});

using (var server = new HttpSelfHostServer(configuration))
{
    server.OpenAsync().Wait();
    stop.WaitOne();
    server.CloseAsync().Wait();
}

I really do want my host bound to just "localhost" -- it will only be accessed from the same machine, and I don't want to mess around with URL ACLs.

How do I configure Web API to not rewrite "localhost" to "+"?

Roger Lipscombe
  • 89,048
  • 55
  • 235
  • 380

1 Answers1

9

Set your HostNameComparisonMode property to Exact:

var config = new HttpSelfHostConfiguration("https://localhost/api/");
config.HostNameComparisonMode = HostNameComparisonMode.Exact;

See this article for more information on HostNameComparisonMode

wal
  • 17,409
  • 8
  • 74
  • 109
  • Thanks. I'd just spent an hour digging around in dotPeek. Even with that information, I still can't find where the transformation actually happens. – Roger Lipscombe Jun 23 '13 at 13:06
  • no worries it was actually posted untested but I knew this property existed on the WCF `binding` element so I'm assuming that gets passed down to the endpoint bindings (not sure exactly in what form webapi uses wcf under the hood tho) – wal Jun 23 '13 at 13:09
  • I knew it existed in WCF, but I assumed it controlled validation once a request had arrived, rather than controlling what the listener actually attempted to bind to. – Roger Lipscombe Jun 23 '13 at 13:12
  • @RogerLipscombe it does indeed get passed to the binding. see `OnConfigureBinding` in `System.Web.Http.SelfHost.HttpSelfHostConfiguration` line 325 – wal Jun 23 '13 at 13:15