58

I have a C# ASP.NET MVC 4 project, which is using Elmah for catching any unhandled exceptions. This works great in most situations.

However I've found that for a controller method that is called using a JQuery Ajax call, I can't get the current Context.

For example in my controller method that returns the JsonResult I have this test code;

try
{
    throw new Exception("This is a test");
}
catch(Exception e)
{
    Elmah.ErrorLog.GetDefault(HttpContext.Current).Log(new Elmah.Error(e));
}

The

HttpContext.Current

is causing the following error;

'System.Web.HttpContextBase' does not contain a definition for 'Current' and no extension method 'Current' accepting a first argument of type 'System.Web.HttpContextBase' could be found (are you missing a using directive or an assembly reference?)

How can I get around this problem ?

neildt
  • 5,101
  • 10
  • 56
  • 107

1 Answers1

132

To get a reference to HttpContext.Current you need replace

HttpContext.Current

with

System.Web.HttpContext.Current

This is because Controller class defines a property named HttpContext that is defined as

public HttpContextBase HttpContext { get; }

HttpContext on Controller class returns HttpContextBase which does not have a Current property.

Hence you need to properly resolve the namespace here.

Dinesh
  • 3,652
  • 2
  • 25
  • 35
  • I tried that which is fine if I'm catching the exception, but still Unhandled exceptions don't appear to be logged ? – neildt Oct 17 '13 at 16:24
  • @Tommo1977 i think, you might be missing proper elmah configuration, not sure though – Dinesh Oct 17 '13 at 16:29
  • thank you, i used this way, `System.Web.HttpContext curContext = System.Web.HttpContext.Current;` – Shaiju T Mar 29 '15 at 10:41
  • http://stackoverflow.com/questions/21148209/asp-net-identity-httpcontext-has-no-extension-method-for-getowincontext – Kiran Bhagat Jan 18 '16 at 08:07