ASP.NET Web API (1): Preliminary usage, GET and POST data

Keywords: ASP.NET JSON xml REST

Summary

REST(Representational State Transfer Representational State Transfer Representational State Transfer) has generated more and more discussions about the REST API. Microsoft has also added the function of Web API in ASP.NET.

Let's look at dudu's article HttpClient + ASP.NET Web API, an alternative to WCF Knowing that blog parks are also starting to use Web API, and when using the Beta version of Web API, they encounter this problem: Accidents of infatuation: ASP.NET WebAPI RC does not support the most commonly used json parameters.

Let's just look at the use of the Web API and see if the current version has solved this problem.

For new features of ASP.NET Web Forms 4.5, see my previous article:

Project establishment

After installing Visual Studio 2012, we click on the new project - > installed template - > Web - > ASP.NET MVC 4 Web Application to build a new project.

The project template selects the Web API.

In Model, we still add the User class used in the previous article.

 1  namespace WebAPI.Models
 2 {
 3      public  class Users
 4     {
 5          public  int UserID {  getset; }
 6 
 7          public  string UserName {  getset; }
 8 
 9          public  string UserEmail {  getset; }
10     }
11 }

Modify the automatically generated ValueController to Users Controller.

GET data

The HTTP get method is used to request data acquisition, and the whole Web API's request processing is based on MVC framework.

The code is as follows.

 1  using System;
 2  using System.Collections.Generic;
 3  using System.Linq;
 4  using System.Net;
 5  using System.Net.Http;
 6  using System.Web.Http;
 7  using WebAPI.Models;
 8 
 9  namespace WebAPI.Controllers
10 {
11      public  class UsersController : ApiController
12     {
13          ///   <summary>
14           ///  User Data List
15           ///   </summary>
16           private  readonly List<Users> _userList =  new List<Users>
17         {
18              new Users {UserID =  1, UserName =  " Superman ", UserEmail =  " Superman@cnblogs.com "},
19              new Users {UserID =  2, UserName =  " Spiderman ", UserEmail =  " Spiderman@cnblogs.com "},
20              new Users {UserID =  3, UserName =  " Batman ", UserEmail =  " Batman@cnblogs.com "}
21         };
22 
23          //  GET api/Users
24           public IEnumerable<Users> Get()
25         {
26              return _userList;
27         }
28 
29          //  GET api/Users/5
30           public Users GetUserByID( int id)
31         {
32              var user = _userList.FirstOrDefault(users => users.UserID == id);
33              if (user ==  null)
34             {
35                  throw  new HttpResponseException(HttpStatusCode.NotFound);
36             }
37              return user;
38         }
39 
40          // GET api/Users/?username=xx
41           public IEnumerable<Users> GetUserByName( string userName)
42         {
43              return _userList.Where(p =>  string.Equals(p.UserName, userName, StringComparison.OrdinalIgnoreCase));
44         }
45     }
46 }

A user list is constructed and three methods are implemented. Let's make the request below.

In the process of using different browser requests, you will find that the return format is different.

Using the Chrome request first, we found that Content-Type in HTTP Header is xml type.

We changed the FireFox request and found that Content-Type was still xml.

We used IE requests again and found that this was the case.

Opening the saved file, we found that the requested data is in JSON format.

The reason for this difference is the inconsistency of Content-Type in Request Header sent by different browsers.

We can use it. Fiddler Verify it.

Content-Type:text/json

Content-Type:text/xml

POST data

Implement a user add function, accept the type of User entity, and our POST data for the corresponding JSON data, to see whether dudu in the Beta version of the problem encountered has been solved.

 1  // POST api/Users/Users Entity Json
 2  public Users Add([FromBody]Users users)
 3 {
 4      if (users ==  null)
 5     {
 6          throw  new HttpRequestException();
 7     }
 8     _userList.Add(users);
 9      return users;
10 }

We still use Fiddler to simulate POST data.

Before POST requests, we attach the code to the process and set breakpoints at the Add method.

In Visual Studio 2012, the debug HOST program became IIS Express.

We use Ctrl+ALT+P and attach it to its process.

Next, use Fiddler to simulate POST.

Note that the Content-Type in Request Header is text/json, and the JSON content in POST is:

1 {"UserID":4,"UserName":"Parry","UserEmail": Parry@cnblogs.com}

After clicking Execute, we jumped to the breakpoint we set up earlier and looked at the submitted data.

In this way, the problems dudu encountered in Beta have been solved.

epilogue

The ASP.NET framework has been developing all the way, and indeed the functions are becoming more powerful and convenient. I hope we can abandon the language debate and return to the pure technical discussion. They all say that Microsoft's technology is changing too fast. What is the essence of change? Is it good to remain unchanged?

In the second part, we'll take a look at some of the security validation issues in the Web API.

Some mistakes are expected to be pointed out and discussed.

If you like, a recommendation is the best affirmation of the article. )

DEMO Source Download

Reference page: http://qingqingquege.cnblogs.com/p/5933752.html

Posted by cwls1184 on Sat, 05 Jan 2019 15:54:09 -0800