神刀安全网

Creating Simple APIs for your AngularJs App with .NET CORE Web API

Starting from the scratch

So, we are starting with the empty Asp.net Core template.

Creating Simple APIs for your AngularJs App with .NET CORE Web API Creating Simple APIs for your AngularJs App with .NET CORE Web API

I’m using Visual studio 2015 and I’ve.NET Core RC2 SDK installed in my machine. Both of them are available for download in the following links,

.NET Core SDK – https://www.microsoft.com/net/core

Visual Studio 2015 – https://www.visualstudio.com/en-us/downloads/download-visual-studio-vs.aspx

Adding Dependencies

We basically need two dependencies, one for serving static files (Microsoft.AspNetCore.StaticFiles) and another one for creating the APIs (Microsoft.AspNetCore.Mvc) . Open up the project.json file and update the dependencies node like below

Creating Simple APIs for your AngularJs App with .NET CORE Web API

Modifying the Startup.cs

Open Startup.cs and remove the existing code from public void Configure(IApplicationBuilder app) method and update the code file with the following code,

 using Microsoft.AspNetCore.Builder; using Microsoft.Extensions.DependencyInjection;  namespace Angular.Core.Web.Api {     public class Startup     {         public void ConfigureServices(IServiceCollection services)         {             services.AddMvc();         }          public void Configure(IApplicationBuilder app)         {             app.UseDefaultFiles();              app.UseStaticFiles();              app.UseMvc();         }     } } 

For now, we are done here.

Managing client dependencies with bower

We are so far down the road but yet I didn’t give any brief on the app we will be building. Let’s make a simple todo with limited functionality (add todo, get the list of todos). Okay fine, so we will need Angular and Bootstrap on client side. Let’s resolve the dependencies with Bower . But first we need to install Bower with NPM . So let’s add a npm configuration file in the project,

Creating Simple APIs for your AngularJs App with .NET CORE Web API

Now open up a command prompt on the root of the project and run this command to install Bower ,

' npm install –save bower 

Creating Simple APIs for your AngularJs App with .NET CORE Web API

After installing Bower , you can resolve client dependencies with Bower , but we want the client scripts to end up in a folder under the wwwroot folder. Let’s say the destination folder name is lib . But we have to tell Bower to do so. That’s why we will need a bower configuration file .

Creating Simple APIs for your AngularJs App with .NET CORE Web API

bower.json file has a child node called .bowerrc .There you will see the configuration to install the dependencies in the wwwroot/lib folder. (if you can’t see the bower.json file, press on the show all file button from the top of the solution explorer). To install Angular and Bootstrap you have to run these two commands in the command prompt

 bower install –save angular 
 bower install –save bootstrap 

Creating Simple APIs for your AngularJs App with .NET CORE Web API

Creating the Angular app

In wwwroot add a index.html file. It will be our main layout file for the angular app. Remember that we have already added the required middleware and configured it in the Startup.cs file to serve static files. By default, ASP.NET Core will serve the index.html file. Also add a folder named app where our application scripts will reside.

Creating Simple APIs for your AngularJs App with .NET CORE Web API

Under app folder create a new script and name it app.js . This is the main angular module, paste the following code in the script,

 (function () {     'use strict';      angular.module('app', []); })(); 

Add two other scripts named todo.controller.js and todo.service.js and the following scripts in there

todo.constroller.js

 (function () {     'use strict';      angular         .module('app')         .controller('TodoController', TodoController);      TodoController.$inject = ['TodoService'];      function TodoController(TodoService) {         /* jshint validthis:true */         var vm = this;         vm.title = 'My Simple Todo';         vm.todo = {};         vm.todos = [];          vm.addTodo = addTodo;          function addTodo() {             var todo = {                 title: vm.todo.title             }              TodoService.addTodo(todo).then(function() {                 TodoService.getTodos().success(function(response) {                     vm.todos = response;                 });             });         }          activate();          function activate() {             TodoService.getTodos().success(function(response) {                 vm.todos = response;             });         }     } })(); 

todo.service.js

 (function () {     'use strict';      angular         .module('app')         .service('TodoService', TodoService);      TodoService.$inject = ['$http'];      function TodoService($http) {         this.getTodos = getTodos;         this.addTodo = addTodo;          function getTodos() {              return $http({                 method: 'GET',                 url: '/api/todo'             });         }         function addTodo(todo) {              return $http({                 method: 'POST',                 url: '/api/todo',                 data: todo             });         }     } })(); 

Now add the following markup in your index.html

 <!DOCTYPE html> <html ng-app="app"> <head>     <meta charset="utf-8" />     <title>My Simple Todo</title>     <link href="lib/bootstrap/dist/css/bootstrap.css" rel="stylesheet" /> </head> <body>     <div class="row" ng-controller="TodoController as vm">         <div class="text-center" style="margin-top: 50px;">             <h2>{{vm.title}}</h2>         </div>         <div class="col-md-4 col-md-offset-4" style="margin-top: 50px;">             <form>                 <div class="input-group">                     <input type="text" class="form-control" placeholder="todo title" ng-model="vm.todo.title">                     <span class="input-group-btn">                         <button class="btn btn-default" type="submit" ng-click="vm.addTodo()">Add</button>                     </span>                 </div>             </form>              <ul class="list-group" style="margin-top: 50px;">                 <li class="list-group-item" ng-repeat="todo in vm.todos">{{todo.title}}</li>             </ul>         </div>     </div>       <script src="lib/angular/angular.js"></script>     <script src="app/app.js"></script>     <script src="app/todo.controller.js"></script>     <script src="app/todo.service.js"></script> </body> </html> 

Adding the Todo repository and API controller

Let’s add a folder called Repository and add an interface called ITodoRepository . If you are not a great fan of dependency injection, you can avoid adding an interface and everything will be working as expected. But Asp.net Core provides an easy way to manage dependency injection in your app, which I’ll show you later. Before adding the interface let’s add a new folder called Models and add a Todo entity class,

Here is the code for Todo.cs ,

 namespace Angular.Core.Web.Api.Models {     public class Todo     {         public string Title { get; set; }     } } 

And here is how ITodoRepository interface looks like

 using System.Collections.Generic; using Angular.Core.Web.Api.Models;  namespace Angular.Core.Web.Api.Repository {     public interface ITodoRepository     {         IEnumerable               GetTodos();         void AddTodo(Todo todo);     } }       

Time to implement the interface. Add a class named TodoRepository and implement the ITodoRepository interface in it, Here is the final look of the TodoRepository class

 using System.Collections.Generic; using Angular.Core.Web.Api.Models;  namespace Angular.Core.Web.Api.Repository {     public class TodoRepository : ITodoRepository     {         public static List               Todos  = new List                  ();          public IEnumerable                       GetTodos()         {             return Todos;         }          public void AddTodo(Todo todo)         {             Todos.Add(todo);         }     } }                         

Now let’s add a API controller for exposing this two functionalities over HTTP. Add a folder named controller and add a Web API Controller named TodoController .

Creating Simple APIs for your AngularJs App with .NET CORE Web API

Add the following code in there

 using System.Collections.Generic; using Angular.Core.Web.Api.Models; using Angular.Core.Web.Api.Repository; using Microsoft.AspNetCore.Mvc;   namespace Angular.Core.Web.Api.Controllers {     [Route("api/[controller]")]     public class TodoController : Controller     {         private ITodoRepository _repository;          public TodoController(ITodoRepository repository)         {             _repository = repository;         }          [HttpGet]         public IEnumerable               Get()         {             return _repository.GetTodos();         }          [HttpPost]         public void Post([FromBody]Todo todo)         {             _repository.AddTodo(todo);         }      } }       

Notice that I’ve only a GET and POST method. By default, you will have five methods. So implement them in your leisure time. Also notice that I’m accepting an argument of ITodoRepository in my constructor. You might be wondering that from where I’ll pass an implementation of ITodoRepository in the constructor. Tada its Magic! Well not actually a magic. You have to add a simple line of code in the ConfigureServices method of Startup.cs . We will discuss it next

Adding Dependency Injection

Okay here is the code to achieve dependency in your app,

 public void ConfigureServices(IServiceCollection services) {     services.AddMvc();     services.AddSingleton              (); }       

Notice that the extension method will create a singleton object of TodoRepository and pass it as an instance to TodoRepository constructor. But it will all happen under the hood.

We are almost at the end. We need to tell our Web API to talk with our client side app in json language. I mean we have to do some content negotiation. That’s easy, just chain another method with the AddMvc() extension method, here is how it looks like,

 public void ConfigureServices(IServiceCollection services) {     services.AddMvc().AddJsonOptions(options => SerializerSettings.ContractResolver = new ePropertyNamesContractResolver());     services.AddSingleton              (); }       

By the way CamelCasePropertyNamesContractResolver is available in another third party .net libray called json.net . So open up the Mangae NuGet Packages window and add it in your project

Creating Simple APIs for your AngularJs App with .NET CORE Web API

We are done. Build you app and give it a spin. Add additional functionalities like edit/delete etc. if you need to.

Here is the final look of the app

Creating Simple APIs for your AngularJs App with .NET CORE Web API

Download Source Code

Here is the github link for the complete demo – https://github.com/fiyazbinhasan/asp-net-core-web-api-with-angularjs

转载本站任何文章请注明:转载至神刀安全网,谢谢神刀安全网 » Creating Simple APIs for your AngularJs App with .NET CORE Web API

分享到:更多 ()

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址