为什么 HttpContext 不包含 "Host" 标头?



在我的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
   }

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

为什么要在这里检索null ?我该如何处理这种情况?

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

要处理它,您可能想尝试这样做:

var host = requestContext.HttpContext.Request.Url.Host;
if (host != null)
    if(!host.EndsWith("SomeHardcodedString")) 
else
   // Handle it

最新更新