Currently I am faced with the requirement building an web service that will let a java client retrieve and trigger actions on our data through httprequest. We are a .Net shop it appears the latest solution for this is Microsoft’s MVC4 Web API. I am used to your standard tiered architecture I have pulled data from API’s but this will be my first web service supplying data.
From my studies I have seen suggestions as follows:
- Separating the logic and data access into a separate project type class library.
- Using your Controls to access data and perform logic.
- Using your Model to access data and perform logic.
I am looking for someone who has experience with MVC4 Web API who can shed some light on good practices for building a web service in this way.
Thanks in advance.
First of all, do put your ASP.NET Web API logic into a separate project. This will give you flexibility over hosting layer (as ASP.NET Web API is hosting agnostic) and it just makes the whole project clean. Let’s say your project’s name is MyProject. You can name the API project as
MyProject.APIand you can install theMicrosoft.AspNet.WebApi.CoreNuGet package into this project.I also suggest you to separate your domain layer as well (POCO entities, repositories, your service layer pieces, etc.). Let’s call this
MyProject.Domain. Then, you would reference thisMyProject.Domainproject from theMyProject.APIproject.I wouldn’t recommend you to dump all your POCO entities into your API. So, I would definately work with Data Transfer Objects (Dto). You can use a 3rd party tool like autoMapper to map your entity classes to your Dtos. However, do put your Dtos, Request Commands, Request Models into a separate project. You would reference
MyProject.API.Modelproject fromMyProject.APIproject. Why do we create a separate project for this? Because, later if you decide to build a .NET client wrapper for your HTTP API, you can easily reference this project to use those with your .NET client as well. Let’s call this projectMyProject.API.Model.Lastly, we need a hosting layer for our API. Asumming that you would like to host this project under ASP.NET, you can create a new project through the Empty Web Application template and let’s call this project
MyProject.API.WebHost. Then, you can install theMicrosoft.AspNet.WebApipackage into this project. From this project, you would referenceMyProject.API,MyProject.API.ModelandMyProject.Domainprojects. This project is the one that you should deploy to your server.If you would like to create a .NET wrapper for your HTTP API, you can create another project called
MyProject.API.Clientand installMicrosoft.AspNet.WebApi.Clientpackage into this one. You would also reference theMyProject.API.Modelproject from this one so that you can deserialize into and serialize from strongly-typed objects.Here is the screenshot of the solution explorer for the project I have been working with:
Hope this gives you a bit of an idea.