从类调用时 HttpContext.Current.Request.UserHostName 为空
我有各种网页需要构建 URL 来显示或将其放置在发出的电子邮件中。我继承的代码在名为“FixedConstants”的公共类中的公共常量中具有 Web 服务器名称的值。例如:
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)的被调用方法调用时返回空?
I have various web pages that need to build up a URL to display or place it in an emitted email message. The code I inherited had this value for the name of the webserver in a Public Const in a Public Class called FixedConstants. For example:
Public Const cdServerName As String = "WEBSERVERNAME"
Trying to improve on this, I wrote this:
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
I've tried different things while debugging such as HttpContext.Current.Request.UserHostName and I always get an empty string which pumps out my default string "SomeWebServer".
I know Request.UserHostName or Request.ServerVariables("REMOTE_HOST") works when invoked from a page but why does this return empty when invoked from a called method of a class file (i.e. UIFunction.vb)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我不使用 VB.NET,但如果您的类被编译到另一个库中,您可以通过 (C#) 访问当前页面:
这应该可以工作。我使用类似的方法动态添加验证器以向用户显示消息。
I don't work with VB.NET, but if your class is compiled into another library, you can access the current page via (C#):
And that should work. I use a similar method of adding validators dynamically for displaying messages to users.
首先,您可能需要检查
HttpContext.Current
是否为null
。如果为 null,您将获得与调用 HttpContext.Current.Request.ServerVariables("REMOTE_HOST") 相同的结果(因为您的 try/catch)
As a starting point, you might want to check whether
HttpContext.Current
isnull
or not.If this is null, you will get the same result as if you call
HttpContext.Current.Request.ServerVariables("REMOTE_HOST")
(because of your try/catch)