문제

i what to put my asp.net mvc4 web api responding to multiple hostheader names like when we add multiple bindings do iis website.

does anyone know how can i do it? or if is it possible?

my default app (still a commandline) looks like this:

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

    }
도움이 되었습니까?

해결책

You can can try configuring your routes to have a custom constraint to match on the host header (in the example below the route would only match if the host header equals myheader.com):

_config.Routes.MapHttpRoute(
        "API Default", "{controller}/{id}",
        new { id = RouteParameter.Optional },
        new { headerMatch = new HostHeaderConstraint("myheader.com")});

The constraint code would be something like:

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 answer works for a self hosted solution like your sample, but if you end up using IIS you just need to add multiple bindinds with all the host headers you want. There is no need to change the routes.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top