As @Henk noted, the controllerโs constructor will be executed before the ActionContext is installed, so you will not have access to properties such as Context , Request or User . You need to get userId in the context of the request.
You can use the old-fashioned action filter approach, which is still part of the MVC6 pipeline (which also supports asynchronous action filters through IAsyncActionFilter ).
Since you want to set a property in your controller, the easiest way to implement this is to override the OnActionExecuting method in the controller class. This works because you inherit a Controller that already implements IActionFilter .
public override void OnActionExecuting(ActionExecutingContext context) {
Edit
If you check DefaultControllerFactory , you will see that:
- the controller is first created.
then an ActionContext is set (via DefaultControllerPropertyActivator , which is one of the property activators):
var controller = _controllerActivator.Create(actionContext, controllerType); foreach (var propertyActivator in _propertyActivators) { propertyActivator.Activate(actionContext, controller); }
source share