ASP. NET Web API/mvc api (Demo attached)

Source: Internet
Author: User

Preface

HTTPService clients, including browsers and mobile devices. Yes buildRESTfulThe. NET Framework of the ideal platform for applications.

HTTP

  • Simple and fast: When a customer requests a service from the server, they only need to send the request method and path. Common Request methods include GET, HEAD, and POST. Each method specifies the type of contact between the customer and the server. Because the HTTP protocol is simple, the program size of the HTTP server is small, so the communication speed is fast.
  • Flexible: HTTP allows transmission of any type of data objects. The Type being transferred is marked by Content-Type.
  • Stateless: Stateless means that the Protocol has no memory for transaction processing. The lack of status means that if subsequent processing requires the previous information, it must be re-transmitted, which may increase the amount of data transmitted each connection.

RESTful

.

  • Representational presentation layer: What is the performance Layer? Resources should be presented. An image, text, or file becomes a resource. Each resource points to it with a URI (Unified Resource Locator, the presentation layer calls the URI to present the resource, and only presents the resource without any other operations. For example, the last part of some URLs is ". html "suffix name is unnecessary because the suffix name represents the format and belongs to the category of" presentation layer ", and URI should only represent the location of" resource. Its specific manifestation should be specified with the Accept and Content-Type fields in the HTTP request header information. These two fields are the description of the "presentation layer.
  • State Transfer State Conversion: When you access a website, it means that the client and the server have an interactive behavior. In this process, no data and status conversion occurs. As mentioned above, HTTP is stateless, if the client operates the server, it must convert the status, which is reflected in the performance layer, so it is called.

Create a Web API

When you create a project, everything is done for you. net. Is it good or bad? You can only laugh.

.

1. Create an ApiDemo Program, Select the Web API template type.

2. Create a News ModelAlthough the MVC project is created, we generally only use controllers and models.

                                               Id { ;                                         Title { ;                                         Content { ;                                         Author { ;                                        DateTime CreateTime { ;      }

3. Create a data simulation class NewsRepositoryUsed to query data.

                 IEnumerable<News>              News[] news =                    News { Id = , Title=, Content=, Author=, CreateTime=                  News { Id = , Title=, Content=, Author=, CreateTime=                  News { Id = , Title=, Content=, Author=, CreateTime=                    }

4. Create a NewsController.Note: When creating a controller, select "null API controller" as the template. Unlike the MVC controller, the API controller inherits the ApiController base class. When we create an MVC project, a ValuesController API controller is automatically generated. After opening the controller, we find that there are many automatic generation methods, the request method is the four HTTP request methods described above: GET, POST, PUT, and DELETE. Here we make a Get request to GET all the news or the specified news ID, the returned result is in XML format.

                                                                       news =                                 RequestMessage =                 Content =  XmlContent(SimpleXmlConverter.ToXmlDocument<News>(news,                                                                HttpResponseMessage GetNewsByID(               news =  NewsRepository().GetAllNews().Where((p) => p.Id ==                                RequestMessage =                 Content =  XmlContent(SimpleXmlConverter.ToXmlDocument<News>(news,        }

  • :, Refer to Region.

5. Route ConfigurationIs similar to the MVC routing configuration. The main difference is that the Web API uses the HTTP method instead of the URI path to select the action. The Routing File WebApiConfig is as follows:

                  name:                  routeTemplate:                  defaults:  { id =             );

Call Web APIs

1. Create the console application-ClientDemo.

2. Install the Web API client library, Tool-Package Manager-Package management control platform, enter the command: Install-Package Microsoft. AspNet. WebApi. Client

The framework version is 4.0. the following error is reported during installation:

If the version is changed to 4.5, the installation is successful. Is it only 4.5 or above supported? Check the MSDN, 4.5, if the previous program uses

           Main(                             ( client =                   client.BaseAddress =  Uri(                  client.DefaultRequestHeaders.Accept.Add( MediaTypeWithQualityHeaderValue(                   xmlString =  client.GetStringAsync(                 XmlDocument xmlDoc =                   XmlNodeList nodeList = xmlDoc.GetElementsByTagName(                  (XmlNode node                       Console.WriteLine( + node.SelectSingleNode(                     Console.WriteLine( + node.SelectSingleNode(                     Console.WriteLine( + node.SelectSingleNode(                     Console.WriteLine( + node.SelectSingleNode(                     Console.WriteLine( + node.SelectSingleNode(                     Console.WriteLine(            }

5. About the release of Web APIs,It took a lot of time to solve the problem one by one. First, we did not rush to call the problem. First, we published the browser. If the browser browsing is okay, we would call it again. The release of Web APIs is similar to that of MVC. Pay attention to the following points:

Running and Demo download

Browser request:

Demo:Http://pan.baidu.com/s/1hqwtQEK

) This article only talks about GET. The HTTP data transmission format (json, xml, and so on) is just about XML, but they are all similar.

 

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.