如何为多个主机标头配置 Webapi 自承载



我把什么放我的 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 时才匹配):

_config.Routes.MapHttpRoute(
        "API Default", "{controller}/{id}",
        new { id = RouteParameter.Optional },
        new { headerMatch = new HostHeaderConstraint("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 答案适用于像示例这样的自托管解决方案,但如果最终使用 IIS,则只需添加多个具有所需所有主机标头的绑定。无需更改路线。

最新更新