Introduction to the ASP. NET Web API

Source: Internet
Author: User

Introduction to the ASP. NET Web API

ASP. NET MVC 4 contains the ASP. NET Web API, a new framework for creating HTTP services that can connect multiple clients, including browsers, mobile devices and more, and the ASP. NET Web API is also the ideal platform for building RESTful services.

ASP. NET Web API features

The ASP. NET Web API contains the following features:

    • Advanced HTTP programming Model: Use the new strongly typed HTTP object model to manipulate HTTP requests and responses directly, using the same programming model and HTTP pipelines on HTTP clients;

    • Support Routing: The Web API fully supports ASP. NET routing, including routing parameters and Constraints. In addition, to the Mapping Support Convention of the action, it is no longer necessary to add properties like [HttpPost] to the class or method;

    • Content Negotiation: the client and the server can together determine the format of the API return data. By default, XML, JSON, and form url-encoded formats can be extended to add custom formats, and can even replace the default content negotiation policy;

    • model Binding and validation: the model binder can easily extract data from an HTTP request and convert it into a. Net object used in an action method.

    • Filter: The Web API supports filtering, including the well-known [authorize] filtering tag, which allows you to add and insert custom filters for the Action, enabling authentication, exception handling, etc.

    • Query aggregation: as long as you simply return iqueryable<t>, the Web API will support querying through OData address conventions;

    • Improved Http detail testability: Instead of setting the HTTP details to a static Context object, the Web API uses Httprequestmessage and Httpresponsemessage instances to add custom types to these HTTP types using the generic versions of these objects ;

    • improved dependency inversion (IoC) Support: The Web API uses the MVC Dependency Resolver implementation of the service locator pattern to get instances in different scenarios;

    • code-based configuration: The Web API is configured separately using code to ensure the cleanliness of the configuration files;

    • Self-hosting (self-host): The Web API, in addition to being hosted in IIS, can be hosted in a process and can still use routing and other features.

The first Web API program creates a Web API project from scratch

1. Create an empty ASP. NET 4.0 Web site project

2, add to System.Net.Http, System.Net.Http.Formatting, System.Web.Http, System.Web.Http.Common, System.Web.Http.WebHost The reference

3. Add the Global application class and add the following code to the Application_Start method in the global class:

RouteTable.Routes.MapHttpRoute (Name: "Defaultapi", Routetemplate: "Api/{controller}/{id}", Defaults:new {ID = routeparameter.optional});

4, add a ProductsController, inherit from Apicontroller, the code is as follows:

public class Productcontroller:apicontroller {public iqueryable<product> getallproducts () {...} Public Product Getproductbyid (int id) {...}} </product>

5, in the browser input URI access to resources, can also be accessed through any client such as script, in the browser as an example:

Entering http://localhost:64334/api/products in the address bar will access the Getallproducts method, returning all the Product instances;

Entering HTTP://LOCALHOST:64334/API/PRODUCTS/1 in the address bar will access the Getproductbyid method, returning the Product instance of the specified ID;

Understanding API Routing

For each Http message, the ASP. NET Web API framework determines, through the routing table, which controller handles the request. When you create a new Web API project, it will include a default route like this:

/api/{controller}/{id}

{Controller} and {ID} are two placeholders that, when encountered with a URI that conforms to this style, will begin to look for the appropriate controller method to make the call, with the following rules:

    • {Controller} is used to match the names of controllers;

    • The HTTP request method is used to match the method name; (This rule applies only to GET, POST, PUT, and DELETE)

    • {ID}, if any, will be used to match the ID parameter of the method;

Here are some examples of requests, as well as the HTTP action results based on the current implementation:

HTTP Method Uri Action
GET /api/products Getallproducts
GET /api/products/5 GetProduct (5)
POST /api/products HTTP Status 405
GET /api/users/ HTTP Status 404

In the first example, the ProductsController is matched with "products", and the HTTP request method is get, so the framework starts looking for a method that starts with "get" in the Productcontroller class, and in addition, the URI The ID parameter is not provided, so the framework should find a method without parameters, and finally, the ProductsController getallproducts method satisfies the requirements.

The second example is similar to the first one, but the URI contains the {id} parameter. Therefore, the framework calls the GetProduct method because it requires a name called the ID parameter. It is worth noting that the ID parameter inside the URI is the "5" of the string type, and the framework automatically transforms it into an integer based on the signature of the method.

In the third example, the client initiates an HTTP POST request, and the framework looks for a method that begins with the name "Post". The Productcontroller class does not have such a method, so the HTTP status code returned by the framework is 405, which means that the method not allowed to be called is not allowed.

Looking again at the fourth example, the client sends a GET request to/api/users. The framework looks for a controller with the name Usercontroller, so the class is not yet defined, so the HTTP status code returned by the framework is 404, indicating that the requested resource was not found.

Web API curd What is curd

Curd refers to Create, Update, Read, Delete Four simple database operations, often most WEB services also provide these operations through restful services.

The next step is to refine the productscontroller to support all of the following actions:

Action

HTTP Method

Relative path

Get all

GET

/api/products

Specify ID Get

GET

/api/products/id

Add to

POST

/api/products

Update

PUT

/api/products/id

Delete

DELETE

/api/products/id


Resources

Productcontroller provides two kinds of URI resources:

Resources

Address

All Products List

/api/products

Single product

/api/products/id


The four main methods of HTTP (GET, PUT, POST, DELETE) are mapped to curd operations in the following ways:

    • Get is used to obtain the presentation of the URI resource, and the get operation should not have any effect on the server;

    • Put is used to update a resource on a URI, and a put can be used to create a new resource if the server allows it;

    • POST is used to create a new resource, and the server creates an object on the specified URI, returning the address of the new resource as part of the response message;

    • Delete is used to delete the specified URI resource.

Implementing curd New Resource

The client initiates an HTTP POST request to create a new resource, in order to handle the POST request, you need to define a method at Productcontroller that begins with post, which accepts a parameter of type Product.

According to the http/1.1 protocol, there are a few issues to be aware of:

    • Response code: The response code returned by the Web API is (OK) by default, but according to the http/1.1 protocol, the response code for the POST request and creation of the resource should be 201 (Created);

    • Address: After the server creates the resource, it should include the address of the new resource in the Header of the response.

The final code for the new resource is as follows:

Public httpresponsemessage<product> postproduct (product product) {This._dbcontext.save (product);   var result = new Httpresponsemessage<product> (product, httpstatuscode.created); var location = Url.route (null, new {id = product.   ProductID}); Result.   Headers.location = new Uri (location); return result;} </product></product>

Update resource Content

The update is relatively straightforward and the code is as follows:

Public httpresponsemessage putproduct (int ID, product product) {if (!this._dbcontext.products.any (p = = P.productid =   = ID)) {throw new httpresponseexception (Httpstatuscode.notfound); } product.   ProductID = ID;   This._dbcontext.update (product); return new Httpresponsemessage (Httpstatuscode.ok);}


The method requires two parameters, the ID is taken from the URI, and product is obtained from the client request message.

Delete a resource

According to the HTTP protocol, the deletion should be idempotent, that is, how many delete requests on a URI are the same, and if the resource has been deleted, it cannot return the wrong response code.

If the resource is deleted successfully, you can return a (OK) response code, a status description for an entity, or return 204 (No Content).

If the deletion needs to wait for the transaction to complete, then 202 (Accepted) should be returned.

The implementation code to delete the resource is as follows:

Public httpresponsemessage deleteproduct (int id) {var product = This._dbcontext.products.firstordefault (p = = P.produ   CtID = = ID);   This._dbcontext.delete (product); return new Httpresponsemessage (httpstatuscode.nocontent);}

Original address: http://www.jianfangkk.com/aspnet/201511/292

Introduction to the ASP. NET Web API

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.