accessing HttpContext.Request in a controller's constructor

前端 未结 4 1607
离开以前
离开以前 2020-12-12 20:30

I\'m following this ASP.NET MVC tutorial from Microsoft:

My code is slightly different, where I\'m trying to access HttpContext.Request.IsAuthenticated

相关标签:
4条回答
  • 2020-12-12 20:54

    I would suggest you use:

     System.Web.HttpContext.Current.Request
    

    Just remember System.Web.HttpContext.Current is threadstatic, but if you don't use additional thread the solution works.

    0 讨论(0)
  • 2020-12-12 20:57

    instead of putting your HttpContext.Request.IsAuthenticated in Controller level you should put it in Controller Base class that will be inherited in all of your controller with an override method of OnActionExecuting() method.

    In your Controller base you should have

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

    and all your Controller should inherit the BaseController class

    public class ApplicationController : BaseController
    

    now you should get the ViewData["IsAuthenticated"] in your Master page.

    Edit

    With the link you have given, and relating to what you have done, your ApplicationController is a Page Controller, not a Base Controller. In the example, ApplicationController is a Base Controller that is inherited by the HomeController but what you have done is you are placing the Action method inside your base controller which is the ApplicationController so your Action Index method will not be invoked when you call any page (Index page) that is not from the ApplicationController.

    0 讨论(0)
  • 2020-12-12 21:07

    The Controller is instantiated significantly prior to the point where the Index action is invoked, and at the moment of construction HttpContext is indeed unavailable. What's wrong with referencing it in your controller method Index?

    0 讨论(0)
  • 2020-12-12 21:15

    The solution of this problem is to create an override method of Initialize by passing 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;
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题