【问题标题】:HttpContext.Current.Request.ServerVariables throws null reference exception in c#HttpContext.Current.Request.ServerVariables 在 c# 中抛出空引用异常
【发布时间】:2016-11-15 05:24:33
【问题描述】:

我使用 HttpContext.Current.Request.ServerVariables["server_name"] 来获取我的 mvc 应用程序中的主机名。它抛出如下异常:“对象引用未设置为对象的实例”。在我的控制器中有这条线。字符串 serverHost = Helper.GetHost();并且在我的助手类中有这个方法。从我的控制器访问此方法。不是控制器构造函数。公共静态字符串 GetHost() { var url = string.Empty; var ipaddress = string.Empty; var sslFlag = WebConfigurationManager.AppSettings["ssl"]; var iisFlag = WebConfigurationManager.AppSettings["iis"]; if (iisFlag.Equals("true", StringComparison.InvariantCultureIgnoreCase)) ipaddress = WebConfigurationManager.AppSettings["IpAddress"]; 别的 ipaddress = HttpContext.Current.Request.UserHostAddress;

        if (sslFlag.Equals("true", StringComparison.InvariantCultureIgnoreCase))
            url = "https://";
        else
            url = "http://";
        return url + ipaddress;
    } Please let me know how to resolve the issue and suggest me a solution to get the hostname and port number in c#. Thanks in advance.

【问题讨论】:

  • 你在哪里用这个??
  • 我在Helper.cs类文件中使用过,并从控制器调用了方法。
  • 在控制器构造函数中使用它??
  • 字符串 serverHost = Helper.GetHost();
  • 是的,阿卜杜勒汗。它是控制器中的一个字段。它不在操作方法中。

标签: c#-4.0 httpcontext


【解决方案1】:
public class HomeController : Controller
{
    string serverHost = Helper.GetHost();
    public ActionResult Index()
    {
        var t = serverHost;
        ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";

        return View();
    }
}
public static class Helper
{
    public static string GetHost() { return HttpContext.Current.Request.ServerVariables["server_name"]; }
}

我的虚拟应用程序中的这个简单代码有效。

【讨论】:

    猜你喜欢
    • 2021-04-29
    • 2022-01-05
    • 1970-01-01
    • 2013-08-17
    • 2011-07-22
    • 2014-11-19
    • 1970-01-01
    • 1970-01-01
    • 2023-03-13
    相关资源
    最近更新 更多