I'm following this ASP.NET MVC tutorial from Microsoft:
My code is slightly different, where I'm trying to access HttpContext.Request.IsAuthenticated in the controller's constructor.
namespace SCE.Controllers.Application { public abstract class ApplicationController : Controller { public ApplicationController() { bool usuario = HttpContext.Request.IsAuthenticated; } } } The problem is that HttpContext is always null.
Is there a solution to this?
In ASP.NET Core, if we need to access the HttpContext in service, we can do so with the help of IHttpContextAccessor interface and its default implementation of HttpContextAccessor. It's only necessary to add this dependency if we want to access HttpContext in service.
ASP.NET Core apps access HttpContext through the IHttpContextAccessor interface and its default implementation HttpContextAccessor. It's only necessary to use IHttpContextAccessor when you need access to the HttpContext inside a service.
HTTP context accessor. Finally, you can use the IHttpContextAccessor helper service to get the HTTP context in any class that is managed by the ASP.NET Core dependency injection system. This is useful when you have a common service that is used by your controllers.
Current property, instead it is available in the HttpContext class in ASP.Net Core applications. Session can be enabled using the Configure method. Inside this method, you will have to call the UseSession method of the app object. Note: It is mandatory to call the UseSession method before the UseMvc method.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With