ASP. NET5 Web API Controller Class learning
The Web API Controller Class is a template type used to add new items to ASP. NETWeb Application projects in VS2015. This template type generates a REST-style interface Class,
Why not choose MVCController Class?
Because we don't want it to involve a View, we don't need a View at all;
For masters, they are all the same, and the inherited classes are all the same, but the specific implementation is different;
For example, if other people already provide complete similar code, it doesn't matter which template to choose.
The sample code is as follows:
using System;using System.Collections.Generic;using System.Linq;using System.Threading.Tasks;using Microsoft.AspNet.Mvc;// For more information on enabling Web API for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860namespace dotnethelloworld.Controllers{ [Route("api/[controller]")] public class ValuesController : Controller { // GET: api/values [HttpGet] public IEnumerable
Get() { return new string[] { "value1", "value2" }; } // GET api/values/5 [HttpGet("{id}")] public string Get(int id) { return "value"; } // POST api/values [HttpPost] public void Post([FromBody]string value) { } // PUT api/values/5 [HttpPut("{id}")] public void Put(int id, [FromBody]string value) { } // DELETE api/values/5 [HttpDelete("{id}")] public void Delete(int id) { } }}
Add method:
Right-click the project name and choose add> new project.
Select "server" on the left and "Web API Controller Class" in the middle. Enter the name you want to use in the Name field.
Browsing and calling:
When the VS2015 window is active, press F5 to enter the debugging status. A default browser window is opened, with the address similar to http: // localhost: 3753.
Note: The following ports are random;
For restful APIs, you can access only GET-type API requests in the address bar of your browser,
Let's take a look at the note of the Get () method: // GET: api/values
This shows that you can access this method through api/values. The access address is http: // localhost: 3753/api/values.
Let's take a look at the note of the Get (int id) method: // GET: api/values/5
This shows that you can access this method through api/values/5. The access address is http: // localhost: 3753/api/values/5.
The next 5 is the value passed to the corresponding int id. The type needs to be matched. If it does not match, the default value is 0;