开发者

HTTP Host header as route value

I am trying to serve multiple virtual hosts from the same code base. One thought I had was pass the 开发者_开发百科HTTP Host header as a route value because I did't want to rely on HttpContext in the controllers because of unit testability.

I had planned on exposing this route value in a controller base class or something like that. I tried passing as a route value like this:

routes.MapRoute(
  "Default", // Route name
  "{controller}/{action}/{id}", // URL with parameters
  new { host = HttpContext.Current.Request.Url.Host, controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);

This yields an HttpException: Request is not available in this context.

Any ideas or suggestions on a better way to do this would be appreciated.


You should be fine relying on the Context when testing your controller. The routing system has been designed with testability in mind so you could set a mock context that provides the right URL when your tests run.

The reason why your code does not work is because you are probabling invoking it from the global Application_Start event which happens before the first request comes in. This means that an HttpContext object is not available at that time.


Try modifying your HomeController as follows:

public ActionResult Index() {
    var request = HttpContext.Request.Url;

    if (request != null && request.AbsoluteUri.Contains("domain.com")) {
        //take the desired action and redirect here
    }

    //the rest of home controller logic
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜