Configuration 如何为多个主机头配置Webapi自托管

Configuration 如何为多个主机头配置Webapi自托管,configuration,asp.net-web-api,hostheaders,Configuration,Asp.net Web Api,Hostheaders,我知道如何将我的asp.net mvc4 web api放置在响应多个主机头名称的位置上,就像我们在iis网站上添加多个绑定时一样 有人知道我怎么做吗?或者如果可能的话 我的默认应用程序(仍然是命令行)如下所示: static void Main(string[] args) { _config = new HttpSelfHostConfiguration("http://localhost:9090"); _config.Routes.Map

我知道如何将我的asp.net mvc4 web api放置在响应多个主机头名称的位置上,就像我们在iis网站上添加多个绑定时一样

有人知道我怎么做吗?或者如果可能的话

我的默认应用程序(仍然是命令行)如下所示:

    static void Main(string[] args)
    {
        _config = new HttpSelfHostConfiguration("http://localhost:9090");

        _config.Routes.MapHttpRoute(
            "API Default", "{controller}/{id}",
            new { id = RouteParameter.Optional });

        using (HttpSelfHostServer server = new HttpSelfHostServer(_config))
        {
            server.OpenAsync().Wait();
            Console.WriteLine("Press Enter to quit.");
            Console.ReadLine();
        }

    }

您可以尝试将路由配置为在主机头上具有自定义约束以匹配(在下面的示例中,只有当主机头等于myheader.com时,路由才会匹配):

约束代码类似于:

public class HostHeaderConstraint : IRouteConstraint
{
    private readonly string _header;

    public HostHeaderContraint(string header)
    {
         _header = header;
    }

    public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
    {
        var hostHeader = httpContext.Request.ServerVariables["HTTP_HOST"];
        return hostHeader.Equals(_header, StringComparison.CurrentCultureIgnoreCase);
    }
}

@Mark Jones answer适用于像您的示例这样的自托管解决方案,但如果您最终使用IIS,则只需添加多个包含所有所需主机头的Bindind即可。没有必要改变路线

public class HostHeaderConstraint : IRouteConstraint
{
    private readonly string _header;

    public HostHeaderContraint(string header)
    {
         _header = header;
    }

    public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
    {
        var hostHeader = httpContext.Request.ServerVariables["HTTP_HOST"];
        return hostHeader.Equals(_header, StringComparison.CurrentCultureIgnoreCase);
    }
}