Can't access to HttpContext.Current

128,786

Solution 1

Have you included the System.Web assembly in the application?

using System.Web;

If not, try specifying the System.Web namespace, for example:

 System.Web.HttpContext.Current

Solution 2

This is because you are referring to property of controller named HttpContext. To access the current context use full class name:

System.Web.HttpContext.Current

However this is highly not recommended to access context like this in ASP.NET MVC, so yes, you can think of System.Web.HttpContext.Current as being deprecated inside ASP.NET MVC. The correct way to access current context is

this.ControllerContext.HttpContext

or if you are inside a Controller, just use member

this.HttpContext

Solution 3

Adding a bit to mitigate the confusion here. Even though Darren Davies' (accepted) answer is more straight forward, I think Andrei's answer is a better approach for MVC applications.

The answer from Andrei means that you can use HttpContext just as you would use System.Web.HttpContext.Current. For example, if you want to do this:

System.Web.HttpContext.Current.User.Identity.Name

you should instead do this:

HttpContext.User.Identity.Name

Both achieve the same result, but (again) in terms of MVC, the latter is more recommended.

Another good and also straight forward information regarding this matter can be found here: Difference between HttpContext.Current and Controller.Context in MVC ASP.NET.

Share:
128,786
Ema.H
Author by

Ema.H

Updated on July 05, 2022

Comments

  • Ema.H
    Ema.H almost 2 years

    I can't access to HttpContext.Current on my project MVC4 with C#4.5

    I've added my reference to System.Web in my project and added the using instruction on my controller page...

    But I can access currentHandler only...

    var context = HttpContext.CurrentHandler; //Current
    

    Is HttpContext.Current deprecated on C#4.5 ?

    I've looked this help page : http://msdn.microsoft.com/en-us/library/system.web.httpcontext.aspx

  • Ema.H
    Ema.H over 10 years
    Thanks for explain, but i can't access Current, just CurrentHanlder ... so don't resolve my problem...
  • CMS
    CMS over 8 years
    funny but it only worked for me after adding the full System.Web.HttpContext.Current didn't pick up the using, i wonder why
  • Atron Seige
    Atron Seige about 8 years
    @CMS, I think it may have something to do with Extensions.
  • David Gomes
    David Gomes over 4 years
    @CMS It's pretty old but I think it's because there's some using in the Controller that already implements HttpContext
  • secretwep
    secretwep over 4 years
    That really does clarify Andrei's answer. Thanks for this.