"Translation" Create your first Web API app in Visual Studio using ASP. NET Core MVC (i)

Source: Internet
Author: User



HTTP is isn't just for serving up web pages. It ' s also a powerful platform for building APIs, that expose services and data. HTTP is simple, flexible, and ubiquitous. Almost any platform this you can think of have an HTTP library, so HTTP services can reach a broad range of clients, includ ing browsers, mobile devices, and traditional desktop apps.



Now the HTTP protocol is no longer just for browsing the web, but also to build a powerful APIs platform to provide data services. HTTP is simple, flexible, and ubiquitous. Almost all of the platforms you know have their own HTTP libraries, so the HTTP service has many users, including browsers, mobile devices, and traditional desktop applications.



In this tutorial, you'll build a simple web API for managing a list of "to-do" items. You won ' t build any UI in this tutorial.



In this tutorial, you will build a simple Web API to manage the "to-do" project, without the need to build the UI throughout the process.



The ASP. NET Core has built-in support for MVC building Web APIs. Unifying the frameworks makes it simpler to build apps that include both UI (HTML) and APIs, because now they share th E Same Code base and pipeline.



ASP. NET core has built-in the use of MVC to create Web APIs. Unifying two frameworks makes it easier to create apps, including UI (Html) and APIs, because they now share the same base classes and pipelines. Overview



Here's the API that's you ll create:



The following are the APIs you need to create:






The following diagram shows the basic design of the app.



The following is the basic design diagram for this application:





  • The client is whatever consumes the Web API (browser, mobile apps, and so forth). We aren ' t writing a client in this tutorial. We'll use Postman to test the app.

  • Here we will use postman to test the application, and any other support Web API (browser, mobile app, etc.) is no longer described here.

  • A Model is an object, which represents the data in your application. The only model is a to-do item. Models is represented as simple C # classes (Pocos).

  • In this application, a model represents an object, and in this example, only the to-do item model. This model is a simple C # class

  • A controller is an object that handles HTTP requests and creates the HTTP response. This app has a single controller.

  • The controller is the object that controls HTTP requests and returns, and this application has only a simple controller.

  • To keep the tutorial and the app doesn ' t use a database. Instead, it just keeps to-do items in memory. But we'll still include a (trivial) data access layer, to illustrate the separation between the Web API and the data layer . For a tutorial this uses a database, see Building your first ASP. NET Core MVC app with Visual Studio.

  • To keep the simple example, the application does not use the database, we only need to save the object in memory. But we should still create a data access layer that will better represent the separation between the Web API and the data layer. If you need to use a database, refer to: Building your first ASP. NET Core MVC app with Visual Studio.

Create a project


Start Visual Studio. From the File menu, select New > Project.



Open Visual Studio, and from the file directory, select New > Project.



Select the ASP. NET Core WEB Application project template. Name the projectTodoApi, clear Hostin the cloud, and tap OK.



Select the ASP. NET Core WEB Application project template, named: Todoapi, uncheck Host in the cloud and click OK.






In the New ASP. NET Core Web Application-Todoapi dialog, select the Web API template. Tap OK.



In the New ASP. NET Core Web Application-todoapi dialog box, select the Web API template and click OK.





Add a Model class


Add a folder named "Models". In Solution Explorer, right-click the project. Select Add > New Folder. Name the folder Models.



In the solution directory, add a folder named "Models", right-click the project-Choose Add > New folder, Name: Models.






ADD aTodoItemclass. Right-click the Models folder and select Add > Class. Name the class andTodoItemtap Add.



Add TodoItem class, right-models directory, select Add > class, Name: TodoItem, click Add.



Replace the generated code with:



Replace the following code with the automatically generated code:


 
namespace TodoApi.Models
{ public class TodoItem
    { public string Key { get; set; } public string Name { get; set; } public bool IsComplete { get; set; }
    }
}
Add Repository Class


A Repository is an object that encapsulates the data layer. The repository contains logic for retrieving and mapping data to an entity model. Even though the example app doesn ' t use a database, it's useful to see how can inject a repository into your Controlle Rs. Create the repository code in the Models folder.



Repository is an object that encapsulates data access. This repository contains the ability to retrieve logic and map data to entity objects. Although we do not use the database in this example, you can see the injection of repository into your controller and create repository code in the Models folder.



Defining a repository interface namedITodoRepository. Use the class template (Add New Item > class)



Define a repository interface named: Itodorepository, using the class template (Add New Item > Class)


 
using System.Collections.Generic; namespace TodoApi.Models
{ public interface ITodoRepository
    { void Add(TodoItem item);
        IEnumerable<TodoItem> GetAll();
        TodoItem Find(string key);
        TodoItem Remove(string key); void Update(TodoItem item);
    }
}


This interface defines basic CRUD operations.



This interface defines the basic CRUD operations.



ADD aTodoRepositoryclass that implementsITodoRepository:



Add a Todorepository class that inherits from the Itodorepository interface:


 
using System; using System.Collections.Generic; using System.Collections.Concurrent; namespace TodoApi.Models
{ public class TodoRepository : ITodoRepository
    { private static ConcurrentDictionary<string, TodoItem> _todos = new ConcurrentDictionary<string, TodoItem>(); public TodoRepository()
        {
            Add(new TodoItem { Name = "Item1" });
        } public IEnumerable<TodoItem> GetAll()
        { return _todos.Values;
        } public void Add(TodoItem item)
        {
            item.Key = Guid.NewGuid().ToString();
            _todos[item.Key] = item;
        } public TodoItem Find(string key)
        {
            TodoItem item;
            _todos.TryGetValue(key, out item); return item;
        } public TodoItem Remove(string key)
        {
            TodoItem item;
            _todos.TryRemove(key, out item); return item;
        } public void Update(TodoItem item)
        {
            _todos[item.Key] = item;
        }
    }
}


Build the app to verify you don't have any compiler errors.



Build the app and check for any compilation errors. Inject this repository.



By defining a repository interface, we can decouple the repository class from the MVC controller that uses it. Instead of instantiating aTodoRepositoryinside the controller we'll inject anITodoRepositoryusing the built-in support in ASP. for dependency Injection.



Because a repository interface is defined, we are able to make the Repository class and the MVC controller separate and use it. We do not need to instantiate a Todorepository class in the controller, just use the built-in dependency injection of ASP.



This approach makes it easier to unit test your controllers. Unit tests should inject a mock or stub version ofITodoRepository. That's the test narrowly targets the controller logic and not the data access layer.



This way, you can make it easier to unit test your controller. You only need to inject a mock itodorepository in the unit test. This allows us to test the logic code of the target controller without having to access the data layer at the time of the test.



In order to inject the repository into the controller, we need to register it with the DI container. Open the Startup.cs file. ADD the following using directive:



We need to register a DI container to facilitate our repository injection into this controller. Open the Startup.cs file and add the reference code:


using Todoapi.models;


ConfigureServicesin the method, add the highlighted code:



In the Configureservices method, add the following highlight code:


 
public void ConfigureServices(IServiceCollection services)
{ // Add framework services.  services.AddMvc();

    services.AddSingleton<ITodoRepository, TodoRepository>();
}
Add Controller


In Solution Explorer, right-click the Controllers folder. Select Add > New Item. In the Add New Item Dialog, select the Web API Controller Class template. Name the classTodoController.



In the solution panel, right-click the Controllers directory and select Add > New Item. In the Add dialog box, select the Web Api Controller class template named: Todocontroller.



Replace the generated code with the following:



Replace the following code:


 
using System.Collections.Generic; using Microsoft.AspNetCore.Mvc; using TodoApi.Models; namespace TodoApi.Controllers
{
    [Route("api/[controller]")] public class TodoController : Controller
    { public TodoController(ITodoRepository todoItems)
        {
            TodoItems = todoItems;
        } public ITodoRepository TodoItems { get; set; }
    }
}


This is defines an empty controller class. In the next sections, we'll add methods to implement the API.



An empty control class is defined here, and the next step is to add an API-related method. Get To-do Item



To get to-do items, add the following methods to theTodoControllerclass.



In the Todocontroller class, add the following method to get a to-do entry:


 
[HttpGet] public IEnumerable<TodoItem> GetAll()
{ return TodoItems.GetAll();
}

[HttpGet("{id}", Name = "GetTodo")] public IActionResult GetById(string id)
{ var item = TodoItems.Find(id); if (item == null)
    { return NotFound();
    } return new ObjectResult(item);
}


These methods implement the GET methods:



These methods contain the following two methods:


    • GET /api/todo

    • GET /api/todo/{id}


Example HTTP response for theGetAllmethod:



The following is what is returned using the GetAll method:


HTTP/1.1 200 OK
   Content-Type: application/json; charset=utf-8 Server: Microsoft-IIS/10.0 Date: Thu, 18 Jun 2015 20:51:10 GMT
   Content-Length: 82 [{"Key":"4f67d7c5-a2a9-4aae-b030-16003dd829ae","Name":"Item1","IsComplete":false}]


Later in the tutorial I'll show how can view the HTTP response using Postman.



After the example, I'll show you how to use Postman to view the HTTP response. Routing and URL paths



The[HttpGet]attribute (HttpGetAttribute) specifies an HTTP GET method. The URL path for each method is constructed as follows:



The HttpGet feature provides an HTTP GET method. This method constructs the following URL path:


    • Take the template string in the controller ' s route attribute,[Route("api/[controller]")]
    • 在控制器的路由特性中查看模板字符串,[Route("api/[controller]")]
    • Replace "[Controller]" with the name of the controller, which is the controller class name minus the "controller" suffix. For this sample, the controller class name was TODOcontroller and the root name is "Todo". ASP. NET Core routing is isn't case sensitive.
    • Replace the controller name, and the class must end with a controller. In this example, we use Todocontroller as the class name, and the ASP. NET core route is case insensitive.
    • If[HttpGet]The attribute has a template string, append the path. This is the sample doesn ' t use a template string.
    • If this httpget attribute contains template characters, add the corresponding path, we do not use the default characters.


In theGetByIdmethod:



In this GetByID method:


[HttpGet ("{ID}""gettodo")]  Public Iactionresult GetById (string ID)


"{id}"is a placeholder variable for the ID of thetodoitem. WhenGetByIdwas invoked, it assigns the value of "{ID}" in the URL to the method ' sidparameter.



{ID} is a placeholder for the TODO item ID, and when GetByID is called, the corresponding {ID} value of the URL is assigned to the ID parameter in the method.



Name = "GetTodo"Creates a named route and allows the link to the this route in an HTTP Response. I ' ll explain it with an example later. See Routing to controllers Actions for detailed information.



[Name="GetTodo"] A route name named Gettodo is created that allows you to link to your route in an HTTP response. A demonstration will be made later, see: Routing to Controller Actions.


return value


TheGetAllmethod returns anIEnumerable. MVC automatically serializes the object to JSON and writes the JSON into the body of the response message. The response code for this method is a, assuming there is no unhandled exceptions. (unhandled exceptions is translated into 5xx errors.)



The GetAll method returns a IEnumerable. MVC automatically serializes the object into JSON format and writes the formatted content to the body of the response message. If not, the response return code is 200. (If so, the error will return a 5xx error message).



In contrast, theGetByIdmethod returns the more generalIActionResulttype, which represents a wide range of return types.GetByIdha S-Different return types:



By contrast, the GetByID method returns a Iactionresult type, which returns more different return types. The GetByID has 2 different return types:


    • If no item matches the requested ID, the method returns a 404 error. This is do by returningNotFound.

    • If there is no match to the response item, this method returns a 404 error, returning NotFound.

    • Otherwise, the method returns with a JSON response body. This is do by returning anObjectResult

    • 相反,这个方法返回200代码并响应一个JSON对象,类型为:ObjectResult。

Original link


Https://docs.microsoft.com/zh-cn/aspnet/core/tutorials/first-web-api



"Translation" Create your first Web API app in Visual Studio using ASP. NET Core MVC (i)


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.