3

我如何让我的 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();
        }

    }
4

2 回答 2

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);
    }
}
于 2012-12-15T11:33:35.080 回答
0

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

于 2013-01-24T13:29:42.710 回答