ASP. NET Core Web API development-restful API implementation

Source: Internet
Author: User
Tags dotnet representational state transfer



ASP. NET Core Web API development-restful API implementation



REST Introduction:



A restful API is called the Web API that fits the rest design style .



Representational State transfer (English:representational, Transfer, short REST) is Roy Thomas Dr. Fielding a World Wide Web software architecture style presented in 2000 in his doctoral dissertation "Architectural styles and the Design of network-based software architectures".



There are currently three mainstream Web service implementations, since rest patterns are more concise than complex soap and xml-rpc, and more and more Web services are beginning to be designed and implemented in restful style. For example, Amazon.com provides close-to-rest-style Web services to perform book queries, and Yahoo provides Web services that are restful.



A restful API is called the Web API that fits the rest design style. It is defined from the following three resources:



Intuitive short resource address: URI, for example: http://example.com/resources/.
Transmitted resources: Web Services accept and return the Internet media type, such as: Json,xml,yaml, etc.
Action on a resource: a series of request methods (such as post,get,put or delete) supported by the Web service on that resource.






The put and delete methods are idempotent. The Get method is a security method (it is not modified on the server side, so of course it is idempotent).



Unlike SOAP-based Web services, RESTful Web services do not have a "formal" standard. This is because rest is a schema, and soap is just a protocol. While rest is not a standard, most restful Web service implementations use various standards such as HTTP, URI, JSON, and XML.


implementation Examples


For example, a simple Web Store app that lists all products,


GET http://www.store.com/products


Render a product,


GET http://www.store.com/product/12345


Order Purchase,


	
   
POST http://www.store.com/order
<purchase-order>
  <item> ... </item>
</purchase-order>

 





The usual HTTP verbs have the following five (the corresponding SQL command in parentheses)


    • GET (SELECT): Remove resources from the server (one or more items).
    • POST (Create): Creates a new resource on the server.
    • PUT (UPDATE): Updates the resource on the server (the client provides a full resource after the change).
    • PATCH (UPDATE): Updates the resource on the server (the client provides changed properties).
    • Delete: Deletes a resource from the server.


Let's do this in the ASP. NET Core Web API.



For example, in the case of the user, each change to the user corresponds to a different HTTP verb.



First we create an ASP. NET Core Web API app. Refer to the previous blog post: http://www.cnblogs.com/linezero/p/5497472.html



Then we add EF Core to manipulate the database. EF Core Tutorial: http://www.cnblogs.com/linezero/p/EntityFrameworkCore.html



First, let's create a new class User.cs


 
public class User
    {
        public int Id { get; set; }
        public string UserName { get; set; }
        public string Password { get; set; }
    }





Then add the EF Core Reference and create the DataContext.cs, and do the configuration.



EF Core 1.0 has been released, so both the reference and configuration can be updated.


install-PackageMicrosoft.EntityFrameworkCore.Sqlite 


Configuration to do updates


Install-package Microsoft.entityframeworkcore.tools–pre
  " Tools " : { "Microsoft.EntityFrameworkCore.Tools""1.0.0- Preview2-final",


Finally, use the dotnet EF command to create the database.


dotnet EF migrations Add myfirstmigration dotnet EF Database update





The following is a formal web API development.



Here we add a Web API controller userscontroller.



Will default to the method that we generate the Get POST PUT DELETE corresponding to. Here we will come to concrete implementation.



UsersController.cs


 [Route("api/[controller]")]
    public class UsersController : Controller
    {
        private DataContext Context;
        public UsersController(DataContext _context)
        {
            Context = _context;
        }
        // GET: api/users
        [HttpGet]
        public IActionResult Get()
        {
            return Ok(Context.Users.ToList());
        }

        // GET api/users/5
        [HttpGet("{id}")]
        public IActionResult Get(int id)
        {
            var _user = Context.Users.FirstOrDefault(r => r.Id == id);
            if (_user == null)
                return NotFound();
            return Ok(_user);
        }

        // POST api/users
        [HttpPost]
        public IActionResult Post([FromBody]User user)
        {
            Context.Add(user);
            Context.SaveChanges();
            return Created($"api/users/{user.Id}",user);
        }

        // PUT api/users/5
        [HttpPut("{id}")]
        public IActionResult Put(int id, [FromBody]User user)
        {
            var _user = Context.Users.FirstOrDefault(r => r.Id == id);
            if (_user == null)
                return NotFound();
            _user.UserName = user.UserName;
            _user.Password = user.Password;
            Context.Update(_user);
            Context.SaveChanges();
            return Created($"api/users/{_user.Id}", _user);
        }

        // DELETE api/users/5
        [HttpDelete("{id}")]
        public IActionResult Delete(int id)
        {
            var _user = Context.Users.FirstOrDefault(r => r.Id == id);
            if (_user == null)
                return NotFound();
            Context.Remove(_user);
            Context.SaveChanges();
            return NoContent();
        }
    }


Once this is done, we use the Chrome app ARC to debug.



Add-"Post:



{"Id": 1, "UserName": "Linezero", "PassWord": "123456"}



Http://localhost:5000/api/users



Multiple queries-"Get:"



Http://localhost:5000/api/users



Single query-"Get" (int id):



Http://localhost:5000/api/users/1



Modify-"Put:



{"UserName": "Linezeroaspnetcore", "PassWord": "123456789"}



Http://localhost:5000/api/users/1



Delete-"Delete:



Http://localhost:5000/api/users/1












The corresponding HTTP operations are also implemented. Database related operations are also in the code.



A code implementation for the ASP. NET Core Web API REST style.






The default JSON serialization of the ASP. NET Core Web API will automatically convert the property name to lowercase, where we only need a single configuration to resolve.


 public void ConfigureServices(IServiceCollection services)
        {
            // Add framework services.
            services.AddMvc().AddJsonOptions(r=>r.SerializerSettings.ContractResolver= new Newtonsoft.Json.Serialization.DefaultContractResolver());
        }





Sample code for this article: Https://github.com/linezero/Blog/tree/master/ASPNETCoreAPI






Reference Links:


Https://zh.wikipedia.org/wiki/REST

Http://www.ruanyifeng.com/blog/2014/05/restful_api.html


If you think this article is helpful to you, please click " recommend ", thank you.



ASP. NET Core Web API development-restful API implementation


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.