Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Consume ASP.NET WebApi from MVC controller

I've started working on a new project where I'm exposing client functionality via WebApi so that I can reuse the same functionality across multiple devices, but there's some functionality that is shared between mobile devices and the hosting application.

My question is while I know how to consume the WebApi's from devices I'm drawing up a bit of a blank on the best way, best practice, or just something that works on how to consume the WebApi from within the MVC project that's hosting the api.

My first thought would be to just instantiate the controllers as needed the way I would any other class however I've got a sneaking suspicion that while it will work this is a bad approach.

The other thought would be to use the HttpClient. Although I've had any luck with it as I can never find the api's

var client = new HttpClient(new HttpServer(GlobalConfiguration.Configuration));
client.PutAsJsonAsync("/api/project/login", Json(model));
like image 328
Marqueone Avatar asked Sep 08 '13 21:09

Marqueone


1 Answers

This is a bit of a subjective question since there really isn't a "right" answer. Essentially, you need to take multiple points into consideration.

  • How safe is it to go the easy route and dependency resolve a controller instance?
  • Will this logic be used in other places?
  • Are these really two separate application concerns?

Essentially, if the API and the MVC application have difference concerns then they should be properly separated and the MVC application should call the WebAPI application using the HttpClient. This can reduce attack vectors and separate application concerns quite well.

If the MVC and WebAPI are both exposing the same information and security/separation of concerns isn't an issue then dependency resolving a controller should suffice.

If the logic isn't a separation of concerns issue and it will be used in multiple places then factoring it out into common components would likely be your best bet.

Shooting from the hip this sounds like a small application that could benefit from dependency resolving a controller in the immediate future. As the application grows (or if it is already planned to be large) then separating the logic into a proper SOA format would be beneficial.

tl;dr - SO really can't answer this question without knowing what the application is and will do. Be pragmatic.

like image 186
Dustin Venegas Avatar answered Oct 02 '22 12:10

Dustin Venegas