Page 54 - MSDN Magazine, July 2017
P. 54
ASP.NET CORE
ASP.NET Core with
Angular, Web API and
Azure DocumentDB
Chander Dhall
With more people migrating to .NET Core and from AngularJS 1.x to Angular 2+, these technologies have become essential, along with other Microsoft technologies in Web API and Azure DocumentDB.
The Yeoman generator aspnetcore-spa (bit.ly/2q10dFn) supports JavaScript frameworks such as Angular, React, and VueJS, as well as other features such as Webpack (bit.ly/2osyQXJ) and Hot module replacement (bit.ly/2oKsKNs). Yeoman was used to start the project I’ll be discussing in this article. Note that the current generator defaults to a Visual Studio 2017 project.
The code discussed in this article can be found at bit.ly/2q1aSzR. There, you’ll find a basic shopping cart implemented using ASP.NET Core, Angular, Web API and Azure DocumentDB.
Web API
A solution that tends to get overlooked but plays a crucial role is the Web API. Using Visual Studio, I created an empty API Controller. You’ll notice upon creation inheriting from the Controller and a Route attribute is decorating the API Controller class:
[Route("api/Carts")]
public class CartsController : Controller {}
API Controllers no longer inherit from APIController, but from Controller, just like an MVC Controller. The differences between the old API Controller and MVC Controller are minimal. In fact, in previous versions of MVC, some people used MVC Controllers as Web API Controllers by simply returning a JsonResult in their action.
Attribute Routing has been supported in the past. Scaffolding has it now and is called Route instead of RoutePrefix.
Utilizing Attributes
In your empty controller, you only have the need for some simple CRUD operations, so you’ll create a simple GetById action method: public Cart GetById(int id){ return _carts.FirstOrDefault(x => x.Id == id); } Using default Web API routing conventions, you can get Cart with Id=5 by making a call to the route api/Carts/5. This is a com- monly used route template constructed by the route prefix defined earlier in your class; this action method took an int only as a param- eter. One way you can identify which HTTP verbs are needed to call this method is to look at the prefix of the action method
This article discusses:
• Brief overview of Azure DocumentDB and its features
• Building block technologies that when used together can create
enterprise-level applications
• Detailed look into constructing a Web API Controller
• Detailed look into the Angular JavaScript Framework, its core foundation and syntatical features
Technologies discussed:
Web API, Angular, Azure DocumentDB, ASP.NET Core
48 msdn magazine