ASP. NET Web API until I put an arrow in my knees [1] Basics

Source: Internet
Author: User

ASP. NET Web API is. NET Framework, Web API can be understood as a RESTful Web service, while the WCF Service carried by IIS is a SOAP-based Web service. The so-called RESTful is an application or design that meets the REST principles. What is the REST principle? To understand the REST principle, let's first understand what the word "Representational State Transfer" actually means and what each word represents.

Representational actually refers to "Resources". A resource is an interesting conceptual entity. It can be an application object, a database record, or an algorithm. In RESTful-based Web Services, each Resource uses the Universal Resource Identifier (URI) to obtain a unique address. Resources are the targets of method calls. They are made public to the client. They are processed and transmitted through standard HTTP methods such as GET, PUT, POST, and DELETE, that is, State Transfer status Transfer. We all know that the HTTP protocol is a stateless protocol, that is to say, the HTTP protocol has no memory for transaction processing. If the previous information needs to be processed in the future, it must be re-transmitted.

This means that the interaction between the client and the server is stateless between requests. Each request from the client to the server must contain the information necessary to understand the request. If the server restarts at any time point between requests, the client will not be notified. In addition, stateless requests can be answered by any available server. On the other hand, the server responds quickly without the previous information, which is very suitable for cloud computing and other environments, the client can cache data to improve performance. After all, this may increase the amount of data transferred each time.

In Visual Studio 2012, create a project or add a new project. In the template pane, select an installed template and expand the Visual C # node. In Visual C #, select Web. In the project template list, select ASP. net mvc 4 Web application. In the new ASP. net mvc 4 Project dialog box, select Web API and click OK.

ASP. NET Web APIs can automatically serialize models to JSON, XML, or some other formats, and then write serialized data to the body of the HTTP Response Message. Next we will create a simple "product" Model:

Id {; Name {; Category {; Price {;}Product. cs

In ASP. NET Web APIs, a controller is a class that processes HTTP requests. The Web API Controller inherits the ApiController class rather than the Controller class, and its operations return data rather than views. Five operations are defined in the sample Product WebAPI controller ProductsController. cs. Each operation is mapped to a URI. The client can call this operation by sending the URI of the http get request.

Product [] products = Product {Id =, Name =, Category =, Price = Product {Id =, Name =, Category =, Price = Product {Id =, Name =, category =, Price = IEnumerable <Product> Product Get (product = products. firstOrDefault (p => p. id = (product = Post ([FromBody] Put (id, [FromBody] Delete (}ProductsController. cs

The MVC Web application uses the code in the Global. asax file to set the default value of the Global URL route, and uses the Web. config file to configure the application. The route is initialized in the Application_Start method of the Global. asax file. What about the Web API GlobalConfiguration?

/// <Summary> /// start the application /// </summary> protected void Application_Start () {Register (GlobalConfiguration. configuration ); // register the global configuration} // <summary> // register the global configuration /// </summary> // <param name = "config"> use the HTTP Route Set initialize HTTP configuration </param> public static void Register (HttpConfiguration config) {config. routes. mapHttpRoute (name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new {id = RouteParameter. optional}); config. enableSystemDiagnosticsTracing ();}

So far, the Web API GlobalConfiguration has been registered. ASP. NET Web APIs include the ApiExplorer class to describe each Web API operation. Then, how can I obtain ApiExplorer through GlobalConfiguration? Therefore, start debugging and add monitoring:

Product [] products = Product {Id =, Name =, Category =, Price = Product {Id =, Name =, Category =, Price = Product {Id =, Name =, category =, Price = IEnumerable <Product> Product Get (product = products. firstOrDefault (p => p. id = (product = [apipolicersettings (IgnoreApi = Post ([FromBody] [apipolicersettings (IgnoreApi = Put (id, [FromBody] [apipolicersettings (IgnoreApi = Delete (}ProductsController. cs

Start debugging and add monitoring:

In Visual Studio, select start debugging or use the keyboard shortcut F5. The local IIS Web Server IIS Express is started and the generated port number is randomly selected. Of course, you can also select the Web server and URL in the project properties.

Use the F12 developer tool, click the network tab, and then start to capture HTTP requests and responses. The following requests are sent to "api/values/" and "api/values/id" respectively.

In fact, most Web APIs must be called programmatically by client applications. The following uses the JQuery getJSON function to send an AJAX request to "api/values" to respond to an array of included JSON objects.

@ Section scripts {<script> var apiUrl = 'api/products'; $ (document ). ready (function () {// send AJAX request $. getJSON (apiUrl) // specifies the callback that is called if the request is successful. done (function (data) {$. each (data, function (key, item) {$ ('<li>', {text: item. name + ': $' + item. price }). appendTo ($ ('# div') ;}); </script>}

 

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.