Table of Contents
Overview
Project creation
POST data
Conclusion
Home Backend Development C#.Net Tutorial Practical tutorials on operating ASP.NET Web API

Practical tutorials on operating ASP.NET Web API

Jun 23, 2017 pm 03:12 PM
api asp.net web how Explore operate


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 of this Website
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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1662
14
PHP Tutorial
1261
29
C# Tutorial
1234
24
What to do if you forget to press F2 for win10 boot password What to do if you forget to press F2 for win10 boot password Feb 28, 2024 am 08:31 AM

Presumably many users have several unused computers at home, and they have completely forgotten the power-on password because they have not been used for a long time, so they would like to know what to do if they forget the password? Then let’s take a look together. What to do if you forget to press F2 for win10 boot password? 1. Press the power button of the computer, and then press F2 when turning on the computer (different computer brands have different buttons to enter the BIOS). 2. In the bios interface, find the security option (the location may be different for different brands of computers). Usually in the settings menu at the top. 3. Then find the SupervisorPassword option and click it. 4. At this time, the user can see his password, and at the same time find the Enabled next to it and switch it to Dis.

Linux Deploy operation steps and precautions Linux Deploy operation steps and precautions Mar 14, 2024 pm 03:03 PM

LinuxDeploy operating steps and precautions LinuxDeploy is a powerful tool that can help users quickly deploy various Linux distributions on Android devices, allowing users to experience a complete Linux system on their mobile devices. This article will introduce the operating steps and precautions of LinuxDeploy in detail, and provide specific code examples to help readers better use this tool. Operation steps: Install LinuxDeploy: First, install

Huawei Mate60 Pro screenshot operation steps sharing Huawei Mate60 Pro screenshot operation steps sharing Mar 23, 2024 am 11:15 AM

With the popularity of smartphones, the screenshot function has become one of the essential skills for daily use of mobile phones. As one of Huawei's flagship mobile phones, Huawei Mate60Pro's screenshot function has naturally attracted much attention from users. Today, we will share the screenshot operation steps of Huawei Mate60Pro mobile phone, so that everyone can take screenshots more conveniently. First of all, Huawei Mate60Pro mobile phone provides a variety of screenshot methods, and you can choose the method that suits you according to your personal habits. The following is a detailed introduction to several commonly used interceptions:

Oracle API Usage Guide: Exploring Data Interface Technology Oracle API Usage Guide: Exploring Data Interface Technology Mar 07, 2024 am 11:12 AM

Oracle is a world-renowned database management system provider, and its API (Application Programming Interface) is a powerful tool that helps developers easily interact and integrate with Oracle databases. In this article, we will delve into the Oracle API usage guide, show readers how to utilize data interface technology during the development process, and provide specific code examples. 1.Oracle

How to deal with Laravel API error problems How to deal with Laravel API error problems Mar 06, 2024 pm 05:18 PM

Title: How to deal with Laravel API error problems, specific code examples are needed. When developing Laravel, API errors are often encountered. These errors may come from various reasons such as program code logic errors, database query problems, or external API request failures. How to handle these error reports is a key issue. This article will use specific code examples to demonstrate how to effectively handle Laravel API error reports. 1. Error handling in Laravel

Oracle API integration strategy analysis: achieving seamless communication between systems Oracle API integration strategy analysis: achieving seamless communication between systems Mar 07, 2024 pm 10:09 PM

OracleAPI integration strategy analysis: To achieve seamless communication between systems, specific code examples are required. In today's digital era, internal enterprise systems need to communicate with each other and share data, and OracleAPI is one of the important tools to help achieve seamless communication between systems. This article will start with the basic concepts and principles of OracleAPI, explore API integration strategies, and finally give specific code examples to help readers better understand and apply OracleAPI. 1. Basic Oracle API

How to enable administrative access from the cockpit web UI How to enable administrative access from the cockpit web UI Mar 20, 2024 pm 06:56 PM

Cockpit is a web-based graphical interface for Linux servers. It is mainly intended to make managing Linux servers easier for new/expert users. In this article, we will discuss Cockpit access modes and how to switch administrative access to Cockpit from CockpitWebUI. Content Topics: Cockpit Entry Modes Finding the Current Cockpit Access Mode Enable Administrative Access for Cockpit from CockpitWebUI Disabling Administrative Access for Cockpit from CockpitWebUI Conclusion Cockpit Entry Modes The cockpit has two access modes: Restricted Access: This is the default for the cockpit access mode. In this access mode you cannot access the web user from the cockpit

Astar staking principle, income dismantling, airdrop projects and strategies & operation nanny-level strategy Astar staking principle, income dismantling, airdrop projects and strategies & operation nanny-level strategy Jun 25, 2024 pm 07:09 PM

Table of Contents Astar Dapp Staking Principle Staking Revenue Dismantling of Potential Airdrop Projects: AlgemNeurolancheHealthreeAstar Degens DAOVeryLongSwap Staking Strategy & Operation "AstarDapp Staking" has been upgraded to the V3 version at the beginning of this year, and many adjustments have been made to the staking revenue rules. At present, the first staking cycle has ended, and the "voting" sub-cycle of the second staking cycle has just begun. To obtain the "extra reward" benefits, you need to grasp this critical stage (expected to last until June 26, with less than 5 days remaining). I will break down the Astar staking income in detail,

See all articles