Search code examples
asp.netasp-classiccommigration

COM visible .NET class cannot get System.Web.HttpContext.Current when used in classic asp


My company would like to update legacy visual basic 6/classic asp code. We do not have access to a visual basic 6 compiler, so it seemed like a good idea to use Visual Studio 10 and recompile the visual basic 6 code as a VB.NET class. With some minor modifications everything compiled and we registered it as a com object to be called from classic asp.

Now we are trying to access global variables from the asp server. After an extensive search on Google, the only way mentioned was to use System.Web.HttpContext.Current or System.Web.HttpContext.Current.Application . However, this doesn't appear to work.

Here is the code leading up to error. We have imported System and System.Web.

Public Function DoSomethingUseful() As String
        Dim objCurrent As System.Web.HttpContext

        DoSomethingUseful = Nothing

        objCurrent = System.Web.HttpContext.Current

        If objCurrent Is Nothing Then
            Throw New Exception("No Context.") '<--- THIS EXCEPTION IS THROWN
        End If

The problem is we can't get a current instance of the http context and the exception is thrown. Every example I've seem shows that the line objCurrent = System.Web.HttpContext.Current should work but it doesn't. Perhaps it's because we are not using ASP.NET? If not then why isn't it working?


Solution

  • Yes, it is because you're not using ASP.NET.

    Despite the similar sounding names, and to a certain degree similar design choices, there is no relationship whatsoever between ASP.NET anything and "Classic" ASP anything. They are completely independent environments.

    To access directly the ASP context objects (not the similarly-named ASP.NET context objects which in your application don't even exist), your object must be a registered COM+ object, so:

    • Your class must inherit from System.EnterpriseServices.ServicedComponent *
    • On Windows 7/2008 and up, you must enable the "Allow IIS Intrinsic properties" from Component Services, just like you would have to in VB6 (open \Component Services\My Computer\COM+ Applications\YourComPlusApp\Components; select all the objects that need the ASP objects; right-click; click on Properties; go to the Advanced tab).

    You can then retrieve the ASP objects (Application, Server, Request, Response, Session) from the COM+ ObjectContext. Your code would look something like this:

    objCurrent = System.EnterpriseServices.ContextUtil.GetNamedProperty("Application")
    

    There are also attributes that you can add to your class to simplify the deployment of the code, but that's a bit outside the scope of this question.

    For your reference:

    * I don't remember 100% if this is a hard requirement. It might actually depend on what the object is actually doing with COM+.