7

I would like to write a helper function which build the exception message to write to a log. The code look like:

if(IsWebApp)
{

      use HttpContext to get the Request Path and RawUrl }
else
{
      //else it a winform/console
      Use Assembly to get executing path.

}

archaictree
  • 175
  • 2
  • 6

5 Answers5

12

Use the HttpRuntime class:

if (!String.IsNullOrEmpty(HttpRuntime.AppDomainAppVirtualPath))
    //ASP.Net
else 
    //Non-ASP.Net
SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • +1 for pointing out to the rest of us that not everything in asp.net is a request thread - learn something new every day :) – Ray Apr 16 '10 at 15:14
1

Just check for some object that only exists in a web application, like HttpRuntime.AppVirtualPath that SLaks suggested.

If it's a web application, you would still want to check if HttpContext.Current is null. If the exception occurs in code that is not run beacuse of a request, it doesn't have any context. The Session_OnEnd event for example runs when a server session is removed, so it doesn't have the context.

Guffa
  • 687,336
  • 108
  • 737
  • 1,005
0

You can check to see if HttpContext.Current != null.

Ryan Rinaldi
  • 4,119
  • 2
  • 22
  • 22
0

How about

If (Not System.Web.HttpContext.Current Is Nothing) Then

End If

or

if(System.Web.HttpContext.Current != null){

}
Jeremy
  • 4,808
  • 2
  • 21
  • 24
  • 1
    Wrong. This will be null in a non-request thread inside an ASP.Net AppDomain. Also, VB.Net has an `IsNot` keyword. Finally, he's using C#. – SLaks Apr 16 '10 at 15:10
  • Never have so many been so wrong in so short a period of time! Thanks for setting us straight. I've been been programming in VB since VB5 so sometimes old habits die hard. That's why I included both. – Jeremy Apr 16 '10 at 15:16
0

I use the DomainManager type of Current AppDomain. MSDN documentation of AppDomainManager

public static class AspContext
{
    public static bool IsAspNet()
    {
        var appDomainManager = AppDomain.CurrentDomain.DomainManager;
        return appDomainManager != null && appDomainManager.GetType().Name.Contains("AspNetAppDomainManager");
    }
}

You can also check this other answer on SO

Community
  • 1
  • 1
Fab
  • 14,327
  • 5
  • 49
  • 68