c# - 为什么 HttpContext 不包含 "Host" header ?

标签 c# asp.net .net asp.net-mvc iis

在我的 MVC3 应用程序中,我有一个自定义 Controller 工厂,它的 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 有时为 null - 我看到一些请求的 NullReferenceException 和异常堆栈跟踪点正好在该行。

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

最佳答案

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

关于c# - 为什么 HttpContext 不包含 "Host" header ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8490004/

相关文章:

c# - 限制访问部分 ASP.Net web 应用程序(只允许来自同一域的计算机)

c# - UnauthorizedException 尝试使用 Windows TaskScheduler 包装器

asp.net - 在 HTML/ASP.NET 控件之间添加空格的良好实践

c# - HTTPListener 不在 .NET 4.6 和 Server2012R2 上使用 TLS 1.1/1.2

c# - 尝试使用 HttpClient 上传文件时来自 Web Api 的 RequestEntityTooLarge 响应

c# - MySQL OdbcConnection 错误 System.Data.Odbc.OdbcException

asp.net - 我的 asp.net mvc 2.0 应用程序失败,错误为 "No parameterless constructor defined for this object"

c# - 如何使用 requireSSL ="true"修复 CSRF 和 [加密 session (SSL) Cookie 中缺少安全属性] 问题?

c# - 在构造函数中引用 "this"可以吗?

.net - 运行时的集合编辑器