search
HomeBackend DevelopmentC#.Net TutorialPractical tutorials on operating ASP.NET Web API

Practical tutorials on operating ASP.NET Web API

Jun 23, 2017 pm 03:12 PM
apiasp.netwebhowExploreoperate


Overview

REST (Representational State Transfer) has been increasingly discussed about REST API, and Microsoft has also added Web API functionality to ASP.NET.

We just took a look at the use of Web API and see if the current version has solved this problem.

Project creation

After installing Visual Studio 2012, we click New Project->Installed Template->Web->ASP.NET MVC 4 Web Application to create a new project.

Project Template Select Web API.

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

Practical tutorials on operating ASP.NET Web API
1 namespace WebAPI.Models
2 {
public class Users
4​ public
int UserID {get; set; } 6
7       public
string UserName { get; set; } 8
9     public
string UserEmail { get; set; } 10 }
11 }
Practical tutorials on operating ASP.NET Web APIModify the automatically generated ValueController to Users Controller.
GET data

Use the HTTP get method to request data. The entire Web API request processing is based on the 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         /// 
14         /// User Data List
15         /// 

16         private readonly List _userList = new List
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 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 GetUserByName(string userName)
42         {
43             return _userList.Where(p => string.Equals(p.UserName, userName, StringComparison.OrdinalIgnoreCase));
44         }
45     }
46 }
Practical tutorials on operating ASP.NET Web API

Constructed a user list and implemented three methods. Let’s make the request below.

When using different browsers to request, you will find that the returned format is different.

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

We change the FireFox request again and find that the Content-Type is still xml type.

We used IE to request again and found that this is the case.

Open the saved file and we find that the requested data is in JSON format.

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

We can use Fiddler to verify it.

Content-Type: text/json

Content-Type: text/xml

POST data

implements a function added by User, and the accepted type is User entity. The data of our POST is the corresponding JSON data to see if the problems encountered by dudu in the Beta version have been solved.

Practical tutorials on operating ASP.NET Web API
1 //POST api/Users/Users Entity Json
2 public Users Add([FromBody]Users users)
3 {
4 if (users = = null)
5                                                                                                                                              ​​
return users;10}


We still use Fiddler to simulate POST data. Before making the POST request, we first attach the code to the process and set a breakpoint at the Add method.
In Visual Studio 2012, the debug HOST program becomes IIS Express.
We use Ctrl+ALT+P to attach to its process.
Use Fiddler to simulate POST below.
Note that the Content-Type in the Request Header is text/json, and the json content of the POST is:
1 {"UserID":4,"UserName":"Parry","UserEmail":Parry@cnblogs. com}

After clicking Execute, it jumps to the breakpoint we set earlier. Let’s take a look at the submitted data.

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

Conclusion

The ASP.NET framework has developed along the way, and its functions are indeed becoming more and more powerful and convenient. I hope we can abandon the language debate and return to pure technical discussions. Everyone says that Microsoft's technology changes too fast. What is the nature of the change? Is it good to remain unchanged?

In the second part, we will take a look at some security verification issues in Web API.

If there are any errors, please point them out and discuss them.

If you like it, giving it a recommendation is the best affirmation for the article. :)

The above is the detailed content of Practical tutorials on operating ASP.NET Web API. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
C# .NET in the Modern World: Applications and IndustriesC# .NET in the Modern World: Applications and IndustriesMay 08, 2025 am 12:08 AM

C#.NET is widely used in the modern world in the fields of game development, financial services, the Internet of Things and cloud computing. 1) In game development, use C# to program through the Unity engine. 2) In the field of financial services, C#.NET is used to develop high-performance trading systems and data analysis tools. 3) In terms of IoT and cloud computing, C#.NET provides support through Azure services to develop device control logic and data processing.

C# .NET Framework vs. .NET Core/5/6: What's the Difference?C# .NET Framework vs. .NET Core/5/6: What's the Difference?May 07, 2025 am 12:06 AM

.NETFrameworkisWindows-centric,while.NETCore/5/6supportscross-platformdevelopment.1).NETFramework,since2002,isidealforWindowsapplicationsbutlimitedincross-platformcapabilities.2).NETCore,from2016,anditsevolutions(.NET5/6)offerbetterperformance,cross-

The Community of C# .NET Developers: Resources and SupportThe Community of C# .NET Developers: Resources and SupportMay 06, 2025 am 12:11 AM

The C#.NET developer community provides rich resources and support, including: 1. Microsoft's official documents, 2. Community forums such as StackOverflow and Reddit, and 3. Open source projects on GitHub. These resources help developers improve their programming skills from basic learning to advanced applications.

The C# .NET Advantage: Features, Benefits, and Use CasesThe C# .NET Advantage: Features, Benefits, and Use CasesMay 05, 2025 am 12:01 AM

The advantages of C#.NET include: 1) Language features, such as asynchronous programming simplifies development; 2) Performance and reliability, improving efficiency through JIT compilation and garbage collection mechanisms; 3) Cross-platform support, .NETCore expands application scenarios; 4) A wide range of practical applications, with outstanding performance from the Web to desktop and game development.

Is C# Always Associated with .NET? Exploring AlternativesIs C# Always Associated with .NET? Exploring AlternativesMay 04, 2025 am 12:06 AM

C# is not always tied to .NET. 1) C# can run in the Mono runtime environment and is suitable for Linux and macOS. 2) In the Unity game engine, C# is used for scripting and does not rely on the .NET framework. 3) C# can also be used for embedded system development, such as .NETMicroFramework.

The .NET Ecosystem: C#'s Role and BeyondThe .NET Ecosystem: C#'s Role and BeyondMay 03, 2025 am 12:04 AM

C# plays a core role in the .NET ecosystem and is the preferred language for developers. 1) C# provides efficient and easy-to-use programming methods, combining the advantages of C, C and Java. 2) Execute through .NET runtime (CLR) to ensure efficient cross-platform operation. 3) C# supports basic to advanced usage, such as LINQ and asynchronous programming. 4) Optimization and best practices include using StringBuilder and asynchronous programming to improve performance and maintainability.

C# as a .NET Language: The Foundation of the EcosystemC# as a .NET Language: The Foundation of the EcosystemMay 02, 2025 am 12:01 AM

C# is a programming language released by Microsoft in 2000, aiming to combine the power of C and the simplicity of Java. 1.C# is a type-safe, object-oriented programming language that supports encapsulation, inheritance and polymorphism. 2. The compilation process of C# converts the code into an intermediate language (IL), and then compiles it into machine code execution in the .NET runtime environment (CLR). 3. The basic usage of C# includes variable declarations, control flows and function definitions, while advanced usages cover asynchronous programming, LINQ and delegates, etc. 4. Common errors include type mismatch and null reference exceptions, which can be debugged through debugger, exception handling and logging. 5. Performance optimization suggestions include the use of LINQ, asynchronous programming, and improving code readability.

C# vs. .NET: Clarifying the Key Differences and SimilaritiesC# vs. .NET: Clarifying the Key Differences and SimilaritiesMay 01, 2025 am 12:12 AM

C# is a programming language, while .NET is a software framework. 1.C# is developed by Microsoft and is suitable for multi-platform development. 2..NET provides class libraries and runtime environments, and supports multilingual. The two work together to build modern applications.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Atom editor mac version download

Atom editor mac version download

The most popular open source editor