Search code examples
asp.netvb.nethttpcontext

Share HttpContext code between web and non-web application


I've got a VB.NET module that reads from a resource file to display text in the correct language. Here's my problem - this code is shared between a web application and a non-web application, In the web application, I'm using System.Web.HttpContext to determine the user's preferred language, but now my Windows app won't even compile, because it says HttpContext isn't defined (I've already tried adding an imports for the full namespace - no dice).

I would love to use some kind of try/catch block if I can't otherwise work around it, but that doesn't change that the windows app won't compile with a reference to HttpContext in it. Without moving this chunk of code into a new file and including it only in the web application (I don't own that app, so I'd rather not deal with those implications), is there another choice I have to deal with this?

If it doesn't make sense, please let me know and I'll do my best to clarify.

SOLUTION: I just added a reference to System.Web, which allowed my application to compile. I also wrapped the HttpContext reference in an "If HttpContext.Current isnot Nothing Then...End If" block, which causes it to skip over the code if it's not running as a web application, which is exactly what I was looking for.


Solution

  • If you reference the System.Web assembly, you should then be given access to HttpContext.Current, which is a reference to the currently running web app's HttpContext object. If the application is a normal Win32 app, this reference should be a null pointer. Thus in C# you would use: if (HttpContext.Current == null) or in VB you could use: If HttpContext.Current Is Nothing Then

    However, I have never tried doing something of this sort, so I can't guarantee the outcome. Let me know if that works for you.

    Thanks, C