Reputation: 51
I have a web MVC app that contains normal MVC controller and web api controller.
WHat is proper way to call web api controller from normal MVC controller action in same project?
Upvotes: 3
Views: 2991
Reputation:
See Is it an antipattern to call WEBAPI services from MVC Controllers?
In a nut shell, use an httpclient in order to get to your api.
Upvotes: 0
Reputation: 4178
If you just need a way to send JSON (or similar) back to the client you can simply choose to return something else than a view from your MVC controller. Then it's all handled within your MVC web app and you don't need to use Web API.
public JsonResult DetailsJson(int id)
{
Car car = carRepository.Find(id);
return Json(car, JsonRequestBehavior.AllowGet);
}
This example would then be called using
/Cars/DetailsJson/3
Please not that GET is allowed in the sample (by adding JsonRequestBehavior.AllowGet) for test reasons and may be removed if you only want to support POST requests.
Upvotes: 0
Reputation: 1275
ASP.Net Web API is meant to be called over HTTP, not from your server-side logic. Perhaps your rendered presentation can call your web API via a client-side request (ajax, for example).
If you find yourself in a position where your MVC controller's action needs to execute code that is only available in a Web API action, then you should consider decoupling that code from your Web API and moving it into a more platform-agnostic area of your code (service layer?).
Upvotes: 3