为什么HttpContext不包含"主机"标头?

sha*_*oth 6 .net c# asp.net iis asp.net-mvc

在我的MVC3应用程序中,我有一个自定义控制器工厂,其CreateController()方法的工作方式如下:

  public IController CreateController(RequestContext requestContext, string controllerName)
   {
       string host = requestContext.HttpContext.Request.Headers["Host"];
       if( !host.EndsWith( SomeHardcodedString ) ) { // FAILS HERE
           //some special action
       }
       //proceed with controller creation
   }
Run Code Online (Sandbox Code Playgroud)

问题是host有时为空 - 我看到NullReferenceException一些请求和异常堆栈跟踪点正好在该行.

为什么要null在这里检索?我该如何处理这类案件?

Art*_*nez 7

使用 string host = requestContext.HttpContext.Request.Url.Host;