If it was decided to use WebAPI to create a service layer to be used for a variety of clients. What would be the best way to architect the web client?
As WebAPI is web-friendly it would be possible to consume this directly from the client using javascript. However I would worry that this can get messy fairly quickly and javascript is not the easiest technology to unit test.
An alternative would be to use the HttpClient class to call the REST services from MVC controllers. Is this a valid approach?
I suppose that the two approachs above could be combined but I would worry that this would get messy. Would you agree that it would be better to go with one approach or the another?
Sorry I have seen many posts on whether to use WebAPI or MVC but none on combining the two.
Thoughts?
Until recently, I found myself in a situation when actually calling from a controller to a web api controller is required: security standard in card payment industry doesn't allow the web to access database directly, but must through a web service (deployed on a private LAN).
Now, let us add ASP.NET MVC controller, as shown in the screenshot given below. After clicking Add button, it will show in the Window. Specify the Controller name as Home with suffix Controller. Now, let's modify the default code of Home controller . Our hosted Web API REST Service includes these two methods, as given below.
Either way, then you can call this class or the ApiController directly from your MVC controller: public class HomeController : Controller { public ActionResult Index () { var listOfFiles = new DocumentsController ().GetAllRecords (); // OR var listOfFiles = new FileListGetter ().GetAllRecords (); return View (listOfFiles); } }
http://localhost:56290 Is the base address of web API service, It can be different as per your server. api It is the used to differentiate between Web API controller and MVC controller request . Employee This is the Web API controller name. GetAllEmployees This is the Web API method which returns the all employee list.
An alternative would be to use the HttpClient class to call the REST services from MVC controllers. Is this a valid approach?
Yes, absolutely. It's just that this code should not be put in your controllers but rather in your DAL layer, because controllers should not know where the data comes from (flat file, database, Web API, ...).
So there are 2 approaches:
Which approach you choose would really depend on your specific scenario and requirements. Do you need to support interoperable clients other than your MVC client application? In any case start by defining a service layer in a separate assembly containing your domain models and stuff. Then you could always expose this service layer through a Web API (or a WCF service or whatever) or directly reference it from .NET clients.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With