how to get a controller instance in another controller

https://stackoverflow.com/questions/16870413/how-to-call-another-controller-action-from-a-controller-in-mvc

https://stackoverflow.com/questions/23748511/how-to-get-instance-of-dependency-resolver-in-asp-net-web-api

https://stackoverflow.com/a/32098348/3782855

As @mxmissile says in the comments to the accepted answer, you shouldn't new up the controller because it will be missing dependencies set up for IoC and won't have the HttpContext.

Instead, you should get an instance of your controller like this:

var controller = DependencyResolver.Current.GetService<ControllerB>(); controller.ControllerContext = new ControllerContext(this.Request.RequestContext, controller);

https://docs.microsoft.com/en-us/aspnet/web-api/overview/advanced/dependency-injection

猜你喜欢

转载自www.cnblogs.com/chucklu/p/10284128.html