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

 

posted @ 2019-01-17 19:24  ChuckLu  阅读(133)  评论(0编辑  收藏  举报