Create an ASP. NET Core Web API under Mac

Source: Internet
Author: User
Tags dotnet response code

Create an ASP. NET core Web API under Mac to create an ASP.

This series of articles is reference to the. NET core documentation and source code, may be asked, directly read the official English document is not enough, why write these articles?

The reasons are as follows:

  • Official documents involved in the content is quite comprehensive, belonging to the kind of chatty knowledge warehouse, not suitable for beginners, it is easy to lose importance, let people fall into the specific details.
  • For most people to develop a language is just a tool, programmers have a common problem, is to die tools, the tool to learn deep. I think there is no need to devote too much time to the tools to be able to effectively complete the daily work Items > target. To demand-driven learning, what you need to learn. If you learn new technology features just disappointing or just need to check the time to find out, this kind of death knock what is the use of this. No must > Spend 120% of the time to learn 100% of the knowledge, you only need to spend 20% of the time to learn 80% of the knowledge can be, the rest of the actual projects used in the time to check on it, tools are just tools, not the work itself.
  • All of the basic articles are now described in the Windows platform-based visual Studio IDE. And I'm using a Mac, so I'll explain the visual Studio code based on the Mac platform to the knowledge we're experiencing in our actual project.
  • Another point is that this is my personal study summary.

This series of articles is for you to spend 20% of your time learning 80% of things, the remaining 20% to see the official documents.

In. NET core, MVC and WEBAPI are integrated into a framework that shares the same set of code and pipelines. This makes it easier to develop MVC applications and Web API interfaces.

Create a project

In this article we will create the following APIs:

API Description
Get/api/user Get all the user information
Get/api/user/{id} Gets the specified user by ID
Post/api/user Add a new user
Put/api/user/{id} Update user Information
Patch/api/user/{id} Update user Information
Delete/api/user/{id} Delete User Information

According to the previous article, we created a WEBAPI project through Yeoman, named UserWebAPI :

To add a model class

Then create a new Models folder under the project root, using yo aspnet:class UserItem a new class under the folder UserItem .

namespace UserWebAPI.Models{    public class UserItem { public string Key { get; set; } public string Name { get; set; } public int Age { get; set; } }}
Add Warehousing class

The Repository class is an object that encapsulates the data layer and contains the business logic that gets the data and maps it to the entity model class.

First we define a repository interface below the Models folder IUserRepository .

yo aspnet:interface IUserRepositorycreate the interface by running the command.

Namespaceuserwebapi.models{ Public interface iuserrepository { void Add (useritem item); ienumerable<useritem> GetAll (); useritem Find (string key); useritem Remove (string key); void Update (useritem item);}}             

Then add a UserRepository class to implement the IUserRepository interface.

Namespaceuserwebapi.models{PublicClassUserrepository:iuserrepository {PrivateStatic concurrentdictionary<String, useritem> _users =New concurrentdictionary<String, useritem> ();PublicUserrepository () {ADD (New Useritem {Name ="Charlie", age =18}); }PublicvoidADD (Useritem item) {Item. Key = Guid.NewGuid (). ToString (); _users[item. Key] = Item; }Public UseritemFind (string key) {Useritem user; _users. TryGetValue (Key, out user); return user;} public ienumerable<useritem> getall (return _users. Values; } public useritem Remove (string key) {Useritem user; _users. Tryremove (Key, out user); return user;} public void update (useritem Item) {_users[item. Key] = Item; } }} 
Register Warehousing

By defining an repository interface, we decouple the class from the MVC controller that uses it repository . We will now UserRepository instantiate a class in the controller by injecting one instead of directly UserRepository .

In order to inject a repository to the controller, we must register it through the DI container, open the Startup.cs file, and ConfigureServices add the following code in the method:

Add Controller

The controller is an object that handles HTTP requests and creates HTTP responses, which are yo aspnet:webapicontroller UserController generated by running commands UserController .

namespace UserWebAPI.Controllers{    [Route("api/[controller]")]    public class UserController : Controller { public IUserRepository UserItems { get; set; } public UserController(IUserRepository userItems) { UserItems = userItems; } }}
Get user Information
[HttpGet]public IEnumerable<UserItem> GetAll(){    return UserItems.GetAll();}[HttpGet("{id}", Name = "GetUser")]public IActionResult GetById(string id){ var item = UserItems.Find(id); if (item == null) { return NotFound(); } return new ObjectResult(item);}

The above two methods implement two Get methods:

    • GET /api/user
    • GET /api/user/{id}

After running, the dotnet restore dotnet run application will start on the local computer and the http://localhost:5000 listening service can be turned on.

Then test your API interface on postman to see if it works correctly.

In the GetById method:

[HttpGet("{id}", Name = "GetTodo")]public IActionResult GetById(string id)

Where "{id}" is the ID placeholder for the Useritem, and when GetById called, the value in the URL is “{id}” assigned to the parameter of the method id .
Name = "GetTodo"A named route is created and allows you to link to the route in the HTTP response.

GetAllmethod returns one IEnumerable , MVC automatically serializes the object into JSON and writes the JSON to the body of the response message. The response status code for this method is 200, assuming that no unhandled exception has occurred.

Instead, GetById the method returns a more general IActionResult type. There are two different return types for this method:

    • If no entry matches the specified request ID, the method NotFound represents a 404 error by returning.
    • Otherwise, the method returns a JSON response body and a 200 response code, which is represented by a return ObjectResult .
Add New User
[HttpPost]public IActionResult Create([FromBody]UserItem item){    if (item == null) { return BadRequest(); } UserItems.Add(item); return CreatedAtRoute("GetUser", new { id = item.Key }, item);}

By [HttpPost] attribute this one HTTP POST method, [FromBody] attribute tells MVC to get the user Useritem value from the body of the HTTP request.

CreatedAtRouteThe method returns a 201 response status code (actually an CreatedAtRouteResult object), which 201 is the standard response code when a new resource is successfully created on the server by the Post method. CreateAtRoutea location header is added to the response, which specifies the newly created user URI.

///<summary>Creates a<see cref= "Createdatrouteresult"/> object that produces a Created (201) Response.///</summary>///<param name= "RouteName" >the name of the the route to use for generating the URL.</param>///<param name= "routevalues" >the route data to use for generating the URL.</param>///<param name= "value" >the content value to format in the entity body.</param>// <returns>the created <see cref= "Createdatrouteresult"/> for the Response. </returns>[nonaction]public virtual Createdatrouteresult createdatroute (string RouteName, object routevalues, object value) { return new Createdatrouteresult (RouteName, Routevalues, value);}              
///<summary>Initializes a new instance of the<see cref= "Createdatrouteresult"/> class with the valuesprovided.///</summary>///<param name= "RouteName" >the name of the the route to use for generating the URL.</param>///<param name= "routevalues" >the route data to use for generating the URL.</param>// <param name= "value" >the value to format in the entity body.  </param>public createdatrouteresult (string routeName, object routevalues, object  Value): base (value) {RouteName = RouteName; routevalues = Routevalues = = null? null: new RouteValueDictionary (routevalues); StatusCode = statuscodes.status201created;}              

By looking CreatedAtRouteResult at the constructor you can see that statuscode (inherited from the Objectresult object) is directly set to the Status201created enumeration value.

201Status code is when you successfully create a new resource on the server side with Post/put, the server should return the 201 Created URI of the resource that was just created by adding a location to the response header at the same time.

To send a create request via postman

As soon as the server receives the request, it displays the corresponding information in the VS Code console:

Click Headers tab to see the value of the location showing the URI of the resource you just created.

Update user information (HTTP PUT)
[HttpPut("{id}")]public IActionResult Update(string id, [FromBody] UserItem item){ if (item == null || item.Key != id) { return BadRequest(); } var user=UserItems.Find(id); if(user==null) { return NotFound(); } UserItems.Update(item); return new NoContentResult();}

The HTTP put tag method is used Update , and the response status code is set to 204 (No Content). According to the HTTP specification, the PUT request requires the client to send the entire updated entity, rather than the incremental update section. If you want to support partial updates, you need to use HTTP patches.

204(No Content)The status code indicates that the server has successfully processed your request, but does not need to return specific data. The browser does not have to refresh the page or redirect to a new page, it retains the page that sent the request, does not produce any changes in the document view, but stays on the current page. Because the 204 response is forbidden to contain any message bodies, it always ends with the first empty line after the message header. For data submitted to the server for processing, consider using the status code 204来 as the return information if only the return is successful, thereby reducing the excess data transfer.

NoContentResultClass calls the constructor of the parent class in the constructor and Status204NoContent passes it to the class.

namespace Microsoft.AspNetCore.Mvc{    public class NoContentResult : StatusCodeResult { public NoContentResult() : base(StatusCodes.Status204NoContent) { } }}
Update user information (HTTP PATCH)
[HttpPatch("{id}")]public IActionResult Update([FromBody] UserItem item, string id){ if (item == null) { return BadRequest(); } var user = UserItems.Find(id); if (user == null) { return NotFound(); } item.Key = user.Key; UserItems.Update(item); return new NoContentResult();}

Delete User
[HttpDelete("{id}")]public IActionResult Delete(string id){ var user = UserItems.Find(id); if (user == null) { return NotFound(); } UserItems.Remove(id); return new NoContentResult();}

This response status code is also 204(No Content) .

Personal blog

My personal blog

Create an ASP. NET Core Web API under Mac

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.