1

我有各种网页需要建立一个 URL 以显示或放置在发出的电子邮件中。我继承的代码在名为 FixedConstants 的公共类中的公共常量中具有网络服务器名称的这个值。例如:

Public Const cdServerName As String = "WEBSERVERNAME"

为了改进这一点,我写了这个:

Public Class UIFunction
Public Shared myhttpcontext As HttpContext
Public Shared Function cdWebServer() As String
    Dim s As New StringBuilder("http://")
    Dim h As String
    h = String.Empty
    Try
        h = Current.Request.ServerVariables("REMOTE_HOST").ToString()
    Catch ex As Exception
        Dim m As String
        m = ex.Message.ToString()   'Ignore this should-not-occur thingy
    End Try
    If h = String.Empty Then
        h = "SomeWebServer"
    End If
    s.Append(h)
    s.Append("/")
    Return s.ToString()
End Function

我在调试时尝试了不同的方法,例如 HttpContext.Current.Request.UserHostName,但我总是得到一个空字符串,它会输出我的默认字符串“SomeWebServer”。

我知道 Request.UserHostName 或 Request.ServerVariables("REMOTE_HOST") 在从页面调用时有效,但为什么从类文件的调用方法(即 UIFunction.vb)调用时返回空?

4

2 回答 2

2

我不使用 VB.NET,但是如果您的类被编译到另一个库中,您可以通过 (C#) 访问当前页面:

Page currentPage = System.Web.HttpContext.Current.Handler as Page;
string hostName = currentPage.Request.UserHostName;

这应该有效。我使用类似的方法动态添加验证器来向用户显示消息。

于 2010-04-15T22:07:40.580 回答
0

作为起点,您可能需要检查是否HttpContext.Current存在null

如果这是 null,您将获得与调用相同的结果HttpContext.Current.Request.ServerVariables("REMOTE_HOST")(因为您的 try/catch)

于 2010-04-15T22:05:50.803 回答