ASP.NET Core 6.0: Is it possible to access the controller instance from IModelBinder.BindModelAsync

145 Views Asked by At

In ASP.NET MVC (on .NET 4.8) I have:

public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
{
    if (bindingContext == null)
        throw new ArgumentNullException("bindingContext");

    var controller = actionContext.ControllerContext.Controller as AppController;
   
    if (controller == null)
        return true;
    // ....
}

The controller context has the controller property through which I can get the instance of the controller.

How can I access in asp.net core 6.0 the instance of the controller being executed inside BindModelAsync ? None of the objects passed in the ModelBindingContext parameter seem point to the instance of the controller, unless I missed something. Here is the controller context doc. The ControllerContext.ControllerActionDescriptor points to anything but the instance of the controller.

Thanks

1

There are 1 best solutions below

4
On

You may try as below to get an instance of the controller:

var factory= bindingContext.HttpContext.RequestServices.GetService<IControllerFactory>();
var controllercontext = bindingContext.ActionContext as ControllerContext;
//add null check before this line
var controllerinstance = factory.CreateController(controllercontext);