1

Is it possible to use/call my Web API methods inside a MVC controller? I have a Web Api to use in mobile and others plattaforms and I´m developing a .NET Mvc Website. Does that architecture makes sense?

Thanks

1
  • 7
    Generally speaking, there are two tidy ways to approach this: either call the WebAPI methods from the page itself using Javscript, or move the internal logic of those methods to a separate place where your MVC controllers and WebAPI can both call it at will. Commented Mar 12, 2014 at 17:10

2 Answers 2

2

Yes it's possible although if you're expecting to consume your API from a number of different clients I would suggest you create your API as a separate application that can then be managed/scaled accordingly.

Essentially you are referring to "dog-fooding" your own API, making your own web application no different to any other client.

We do something similar and have our MVC application call our API (using HttpClient). We also have a lot of client side code within the same application that calls the API directly using CORS.

We've had this architecture running in production for 2 years now without any issue.

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

Comments

1

Here is How I call my Web API controller from MVC controller:

public class invoiceController : ApiController
    {
        private myEntities db = new db1Entities();

        // GET api/invoices
        public IQueryable<invoices> Getinvoices()
        {
            return db.invoices;
        }
}

inside separate MVC controller:

public ActionResult ShowInvoices()
{
  var webApi = new invoicesController();
  //this must return strongly typed object
  var myarray = webApi.Getinvoices(); 
  return View(myarray);
}

1 Comment

This is not a good approach. If you want to share logic between MVC and Web API in the same application, move it into a separate class; don't invoke your Web API controller from MVC.

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.