Access to HttpContext.Request in the controller constructor

I follow this tutorial from ASP.NET MVC from Microsoft :

My code is a little different where I try to access HttpContext.Request.IsAuthenticated in the controller constructor.

 namespace SCE.Controllers.Application { public abstract class ApplicationController : Controller { public ApplicationController() { bool usuario = HttpContext.Request.IsAuthenticated; } } } 

The problem is that the HttpContext always null.

Is there a solution for this?

+42
asp.net-mvc controllers
Aug 08 '10 at 1:01
source share
4 answers

The controller is created significantly until the moment the index action is called, and at the time of construction, the HttpContext is really unavailable. What is wrong by referring to it in the Index controller method?

+7
Aug 08 '10 at 1:22
source

instead of placing your HttpContext.Request.IsAuthenticated at the controller level, you should place it in the base class class of the controller, which will be inherited throughout your controller using the OnActionExecuting () method override method.

In the base of your controller you must have

 public class BaseController : Controller { protected override void OnActionExecuting(ActionExecutingContext ctx) { base.OnActionExecuting(ctx); ViewData["IsAuthenticated"] = HttpContext.Request.IsAuthenticated; } } 

and your entire controller should inherit the BaseController class

 public class ApplicationController : BaseController 

you should now get ViewData["IsAuthenticated"] on the main page.

Edit

With the link you provided and related to what you did, your ApplicationController is a Page Controller, not a base controller. In this example, the ApplicationController is the base controller that the HomeController inherits, but you did what you place the Action method inside your base controller, which is the ApplicationController , so your Index Index method will not be called when you call any page (index page) that not owned by ApplicationController.

+79
Aug 08 '10 at 1:21
source

I suggest you use:

  System.Web.HttpContext.Current.Request 

Just remember that System.Web.HttpContext.Current is threadstatic, but if you are not using an extra thread, this solution works.

+42
Jul 09 '13 at 10:15
source

The solution to this problem is to create an Initialize override method by passing the RequestContext object.

 public class ChartsController : Controller { bool isAuthed = false; protected override void Initialize(System.Web.Routing.RequestContext requestContext) { base.Initialize(requestContext); if (requestContext.HttpContext.User.Identity.IsAuthenticated) { isAuthed =true; } } } 
+6
Feb 29 '16 at 17:56
source



All Articles