I have two controllers, one mvc controller and one api controller, both are in the same project.
HomeController: Controller{ ... }
DataController: ApiController{ ... }
If I want to consume post action in DataController from HomeController is it necessary to use HttpClient
?
Not required. You can directly create the object of DataController object in HomeController and use its post method like instance method in .Net.
public class HomeController : Controller
{
public ActionResult GetResult()
{
MyApp.DataController dataController = new MyApp.DataController();
var data = dataController.Post("arguments");
return View(data);
}
}
There is a tool called Refit that will help you here, it masks all the need for httpclient interaction and allows you to create a service that you can inject into your controllers so you can keep them testable. Project page for Refit
Highly recommended this tool. I've used it quite a bit and think it's part of the essential toolkit when separating logic behind an api.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.