我如何放置我的 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/