[ASP. NET] About REST and ASP. NET Web APIs, asp. netrest
The 13-day holiday is over, so I have to pay for it.
This section
- Web API Introduction
- Self-boarding
- IIS boarding
- Call Web APIs
- Web API principles
Web API Introduction
REST
REST is the abbreviation of "REpresentational State Transfer". It can be translated into "express State transition ".
REST is a software architecture that has nothing to do with technology, but most REST-based Web services are based on HTTP
(Although WCF supports REST after 3.5, it is too large, and Web API is more suitable for REST Architecture)
SOAP and REST
The SOAP Web API adopts the RPC (Remote Procedure Call) style, and adopts a functional-Oriented Architecture. Therefore, what functions should be taken into consideration at the beginning of the design.
RESTful Web APIs use the ROA (Resource-Oriented Resouce Oriented Architecture) Architecture. Therefore, you must first consider the resources available for operation at the beginning of the design.
HTTP protocol
HTTP uses a simple request/response mode for message exchange to implement certain operations on a Web resource.
The operation types for resources are similar to CRUD (Create, Retrieve, Update, and Delete.
In addition to using the URI to mark the target resource, an HTTP request also needs to specify the operation type for the resource through the HTTP method.
HTTP methods: including GET, POST, PUT, DELETE, HEAD, OPTIONS, TRACE, CONNECTION, and PATCH
HTTP protocol
GET http://neverc.cn/ HTTP/1.1Host: neverc.cnConnection: keep-aliveAccept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8Upgrade-Insecure-Requests: 1User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.15 Safari/537.36Accept-Encoding: gzip, deflate, sdchAccept-Language: zh-CN,zh;q=0.8Cookie:
Row 1st is the three basic attributes of HTTP, including method, uri, and vesion.
Others are HTTP request headers. http defines many native headers. You can also add custom headers (actually, key-value pairs)
In addition to the header, an HTTP request can also contain the content of a request body, which can be in any format.
Like HTTP requests, HTTP responses are composed of headers and packets.
HTTP/1.1 200 OKCache-Control: privateContent-Type: text/html; charset=utf-8Vary: Accept-EncodingServer: Microsoft-IIS/7.5X-AspNetMvc-Version: 5.0X-AspNet-Version: 4.0.30319X-Powered-By: ASP.NETDate: Fri, 18 Sep 2015 05:39:50 GMTContent-Length: 12003<!DOCTYPE html>
Rows 1st are vesion and statu (except 200 OK, 401 Not Authorized and 404 Not Found are common)
Row 3 Content-Type indicates the media (or resource/data) Type.
- Text/html: HTML documents.
- Text/xml (application/xml): text in XML format.
- Text/json (application/json): JSON text.
- Image/gif (image/jpeg, image/png): Images in GIF (JPEG, PNG) format.
- Audio/mp4 (audio/mpeg, audio/vnd.wav e): audio files in MP4 (MPEG, WAVE) format.
- Video/mp4 (video/mpeg, video/quicktime): MP4 (MPEG, QUICKTIME) video files.
Self-boarding
Create a project
- Model:A class library project that defines entities
- WebApi:A class library project that defines the API controller (reference the Model Project)
- SelfHost:A console project and a hosted API Service (referencing a WebApi Project)
Referenced assembly involved
Create entity
Create a Contact class in the Model project.
public class Contact { public string Id { get; set; } public string Name { get; set; } }
Create a controller
In the WebApi project, reference the System. Web. Http class library and create an API controller.
Public class ContactsController: ApiController {# region Data static readonly List <Contact> contacts; static int counter = 2; static ContactsController () {contacts = new List <Contact> {new Contact {Id = "001", Name = "James"}, new Contact {Id = "002 ", name = "" };}# endregion public IEnumerable <Contact> Get (string id = null) {return from contact in contacts where contact. id = id | string. isNullOrEmpty (id) select contact;} public void Post (Contact contact) {// multi-thread concurrent processing Interlocked. increment (ref counter); contact. id = counter. toString ("D3"); contacts. add (contact);} public void Put (Contact contact) {contacts. remove (contacts. first (c => c. id = contact. id); contacts. add (contact);} public void Delete (string id) {contacts. remove (contacts. first (c => c. id = id ));}}
Self-boarding
In SelfHost, reference the System. Web. Http, System. Net. Http, System. Web. Http. SelfHost class library and implement the host
Static void Main (string [] args) {// For SelfHost, by default, HTTP controller-type parsing only loads the Assembly list that is loaded to the current application domain manually. Assembly. load ("WebApi, Version = 1.0.0.0, Culture = neutral, PublicKeyToken = null"); var configuration = new HttpSelfHostConfiguration ("http: // localhost/selfhost "); using (var httpServer = new HttpSelfHostServer (configuration) {httpServer. configuration. routes. mapHttpRoute (name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new {id = RouteParameter. optional}); httpServer. openAsync (). wait (); Console. writeLine ("successful hosting Web API service"); Console. read ();}}
Test
Run the SelfHost console and access http: // localhost/selfhost in the browser.
Note: (because http. sys is registered here, you need to run VS as an administrator)
IIS boarding
It is very easy to use IIS to host. You only need to register route data.
Create a project
- WebHost:An empty Web Project (referencing Model and WebApi Projects)
Register a route
Create a Global File and register HttpRoute
public class Global : HttpApplication { protected void Application_Start(object sender, EventArgs e) { GlobalConfiguration.Configuration.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional }); } }
Test
Run the WebHost project and access http: // ~ in the browser ://~ /Api/Contacts.
Call Web APIs
Because Web APIs are based on HTTP, developers can request website data just like common website data.
- JQuery
- MVVM/MVC Framework JS, AngularJS, Knockout. js
- HttpClient, WebClient, and HttpWebRequest can be used in the background.
Here is a complete example of HttpClient. If you have any questions about Asynchronization, read my blog: [C #] About asynchronous programming async await.
Create a console project to implement the Program class:
Static HttpClient httpClient = new HttpClient (); static void Main (string [] args) {// because most of the methods in the HttpClient class are asynchronous // The Main method does not support the Async keyword // create a method so that it can run Process () synchronously; Console. read ();} async static void Process () {// obtain the current contact list ListContacts (); // Add a new contact var Contact = new contact {Name = ""}; await httpClient. postAsJsonAsync (" http://localhost/selfhost/api/contacts ", Contact); Console. WriteLine (" Add new contact "Wang Wu": "); ListContacts (); // modify an existing contact var response = await httpClient. GetAsync (" http://localhost/selfhost/api/contacts /001 "); contact = (await response. content. readAsAsync <IEnumerable <Contact> ()). first (); contact. name = "Zhao six"; await httpClient. putAsJsonAsync (" http://localhost/selfhost/api/contacts /001 ", contact); Console. WriteLine (" Modify contact "001" information: "); ListContacts (); // delete an existing contact await httpClient. DeleteAsync (" http://localhost/selfhost/api/contacts /002 "); Console. WriteLine (" Delete contact "002": "); ListContacts ();} async static void ListContacts () {var response = await httpClient. GetAsync (" http://localhost/selfhost/api/contacts "); IEnumerable <Contact> contacts = await response. content. readAsAsync <IEnumerable <Contact> (); Console. writeLine ("current Contact list:"); foreach (contact Contact in contacts) {Console. writeLine ("{0,-6} {1,-6}", contact. id, contact. name);} Console. writeLine ();}
Web API principles
Web APIs use the MVC design to define services in the form of a Controller. Action represents a specific operation.
The Web API obtains the controller through URL routing, and then finds the corresponding action through the http Method Based on the routing object. (In fact, if the action cannot be parsed Based on the url, the http method will be used)
Route Registration
config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } );
Because no action is defined in the template, you can only use httpmethod to find action (and match the method prefix)
When you view data through the browser api/Contacts, a data in xml format is returned.
In fact, webapi checks accept first, from left to right, to match the serializer. If no match is found, the default json serializer is used.
Pipeline Design
Web APIs also adopt a pipeline design, which is different from the MVC pipeline, although it is similar to MVC in many places.
The Route object is HttpRoute.
The Handle object is HttpControllerHandler (because the IHttpAsyncHandler interface is implemented, the BeginProcessRequest asynchronous method is used by default)
Address: http://neverc.cnblogs.com/p/4603935.html
Reference: http://www.cnblogs.com/artech/p/how-asp-net-web-api-works.html