如何为多个主机标头配置Web Api Self Hosted

时间:2012-12-14 16:41:24

标签: configuration asp.net-web-api hostheaders

我的asp.net mvc4 web api响应多个hostheader名称,例如当我们添加多个绑定时,我会做什么网站。

有谁知道我该怎么做?或者是否可能?

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

    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();
        }

    }

2 个答案:

答案 0 :(得分:2)

您可以尝试配置您的路由以在主机标头上匹配自定义约束(在下面的示例中,路径仅在主机标头等于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);
    }
}

答案 1 :(得分:0)

@Mark Jones的答案适用于像您的示例一样的自托管解决方案,但如果您最终使用IIS,则只需要添加多个绑定所需的所有主机头。无需更改路线。

相关问题