Paul
Paul

Reputation: 12799

Using Web Api in a MVC Controller

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

Upvotes: 1

Views: 253

Answers (2)

Adam W
Adam W

Reputation: 285

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);
}

Upvotes: 1

Ben Foster
Ben Foster

Reputation: 34800

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.

Upvotes: 2

Related Questions