configuration - 如何为多个主机头配置 Web Api 自托管

标签 configuration asp.net-web-api hostheaders

我如何放置我的 asp.net mvc4 web api 以响应多个主机 header 名称,就像我们在 iis 网站上添加多个绑定(bind)一样。

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

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

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

    }

最佳答案

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

关于configuration - 如何为多个主机头配置 Web Api 自托管,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13882811/

相关文章:

php - 有没有办法在 php 结束标记后强制换行?> 当嵌入到 html 中时?

iOS - 开发构建工作但分发构建崩溃

xcode - 如何向Xcode添加配置?

javascript - AJAX 调用带有参数的 WebAPI Get 方法不下载文件 ASP .NET MVC

c# - 在iis服务器上从web api运行exe文件不起作用

sharepoint - IIS 6 : Set up 2 SSL web apps on the same server on port 443

ruby - 如何在多个 sinatra 应用程序中包含配置

asp.net - MVC 6 WebAPI 返回序列化的 HttpResponseMessage 而不是文件流

asp.net - 在 ASP.NET 中,是否可以按主机名输出缓存?即,varbyhost 或 varbyhostheader?