views:

336

answers:

2

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)?

A: 

As a starting point, you might want to check whether HttpContext.Current is null 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)

Paul Lucas
A: 

I don't work with VB.NET, but if your class is compiled into another library, you can access the current page via (C#):

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

And that should work. I use a similar method of adding validators dynamically for displaying messages to users.

Jim Schubert