Paceman Paceman - 1 year ago 145
C# Question

Decoupling Web API from an MVC 5 project

I've got a website built with MVC5 and EF6. It's split into 2 projects:

  • "Website" contains all the usual Ms, Vs and Cs, and

  • "Website.Models" contains the EF DBContext and entities.

Now I have to build a mobile app for it.

I am thinking to add a new project "Website.API" so it can serve view models directly to both mobile app and the website, in POCOs and JSON. By offloading the work to produce view models into to this new API, I aim to make the website and the mobile app thin, to avoid duplicating a lot of code it two different languages

My question is can I achieve something like this with Web API:

// Website project controller method
ActionResult ProfileController.Save(
Profile model,
List<HttpPostedFileBase> uploadedImages){

// Call WebAPI here:
// Is it possible to pass model and uploadedImages to the API
// and have it do the saving, querying, assembling a new
// profileDisplayModel and return it

// So I can just then do this:

Or - if this is not the best approach, then what is? And what are the gotchas?

Answer Source

You can do it by using any REST client library like RestSharp, or using HttpClient together with Json.Net to make async calls to the API from your controllers.

However, you are creating an extra network call between parts of one application. It will affect the performance of you application.

You can instead separate the logic of your application in a separate library and call it from both API and MVC controllers. This will be somewhat closer to proper encapsulation and separation of concerns.

It will also allow you to write tests for the logic alone, without any HTTP infrastructure.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download