3

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?

3
  • 1
    Don't. Instead, move it to a separate class. Commented Jan 17, 2013 at 18:57
  • this web api controller is only used exclusively by normal web controller so it's the reason I put them in one project. Commented Jan 17, 2013 at 19:00
  • 2
    Please, stop referring to "ASP.NET MVC" simply as "MVC". One is a framework, while other is a language-independent design pattern. It's like calling IE - "the internet" Commented Jan 18, 2013 at 15:39

3 Answers 3

3

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?).

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.