如何让ASP.NET Web API(自托管)只监听*localhost?

Rog*_*mbe 12 asp.net-web-api

我在这里的示例是关于自托管的ASP.NET Web API服务.但是,当将"localhost"指定为基址中的主机时,它将转换为"+"(表示"全部可用").

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();
}
Run Code Online (Sandbox Code Playgroud)

我真的希望我的主机只能绑定到"localhost" - 它只能从同一台机器上访问,而且我不想乱用URL ACL.

如何配置Web API以将"localhost"重写为"+"?

wal*_*wal 9

将您的HostNameComparisonMode属性设置为Exact:

var config = new HttpSelfHostConfiguration("https://localhost/api/");
config.HostNameComparisonMode = HostNameComparisonMode.Exact;
Run Code Online (Sandbox Code Playgroud)

有关HostNameComparisonMode的更多信息,请参阅此文章