search

How to call webApi

May 31, 2019 pm 04:16 PM
webapi

How to call webApi

How to call webapi? How to call the webApi interface using a program?

In C#, there are generally two ways to call the HTTP interface:

1. WebRequest/WebResponse combined method call

2.WebClient class to call.

The first method is less abstract and more cumbersome to use; while WebClient is mainly oriented to WEB web page scenarios and is more convenient to use when simulating Web operations, but it is more troublesome to use in RestFul scenarios. In Web API At the time of release, .NET provides two assemblies: System.Net.Http and System.Net.Http.Formatting. The core class in these two assemblies is HttpClient.

These two assemblies are included in .NET4.5, and .NET4 needs to download the two packages Microsoft.Net.Http and Microsoft.AspNet.WebApi.Client from Nuget to use this class. Lower .NET versions can only express regret and can only use WebRequest/WebResponse or WebClient to call these APIs.

In use, the System.Net.Http assembly provides the HttpClient class and related HTTP calls, while System.Net.Http.Formatting provides some help extensions for HttpClient to better support Content negotiation, Content creation and other functions.

Let me write this example with you:

public class Person

    {

        public long Id { get; set; }        public string Name { get; set; } 

        public int Age { get; set; } 

        public string Sex { get; set; } 

        public override string ToString()

        {            return $"Id={Id} Name={Name} Age={Age} Sex={Sex}";

        }

    }
class Program
   {
       static void Main(string[] args)
       {
           var client = new HttpClient();
           //基本的API URL
           client.BaseAddress = new Uri("http://localhost:22658/");
           //默认希望响应使用Json序列化(内容协商机制,我接受json格式的数据)
           client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); 
           //运行client接收程序
           Run(client);
           Console.ReadLine();
       }
       //client接收处理(都是异步的处理)
       static async void Run(HttpClient client)
       {
           //post 请求插入数据
           var result = await AddPerson(client);
           Console.WriteLine($"添加结果:{result}"); //添加结果:true
           
           //get 获取数据
           var person = await GetPerson(client);
           //查询结果:Id=1 Name=test Age=10 Sex=F
           Console.WriteLine($"查询结果:{person}"); 
           //put 更新数据
           result = await PutPerson(client);
           //更新结果:true
           Console.WriteLine($"更新结果:{result}"); 
           //delete 删除数据
           result = await DeletePerson(client);
           //删除结果:true
           Console.WriteLine($"删除结果:{result}"); 
       }
       
       //post
       static async Task<bool> AddPerson(HttpClient client)
       {
           //向Person发送POST请求,Body使用Json进行序列化
           return await client.PostAsJsonAsync("api/Person", new Person() { Age = 10, Id = 1, Name = "test", Sex = "F" }) 
                               //返回请求是否执行成功,即HTTP Code是否为2XX
                               .ContinueWith(x => x.Result.IsSuccessStatusCode);  
       }
       
       //get
       static async Task<Person> GetPerson(HttpClient client)
       {
           //向Person发送GET请求
           return await await client.GetAsync("api/Person/1") 
           //获取返回Body,并根据返回的Content-Type自动匹配格式化器反序列化Body内容为对象
                                    .ContinueWith(x => x.Result.Content.ReadAsAsync<Person>(                             
                   new List<MediaTypeFormatter>() {new JsonMediaTypeFormatter()/*这是Json的格式化器*/
                                                   ,new XmlMediaTypeFormatter()/*这是XML的格式化器*/}));
       }
       
       //put
       static async Task<bool> PutPerson(HttpClient client)
       {
           //向Person发送PUT请求,Body使用Json进行序列化
           return await client.PutAsJsonAsync("api/Person/1", new Person() { Age = 10, Id = 1, Name = "test1Change", Sex = "F" }) 
                               .ContinueWith(x => x.Result.IsSuccessStatusCode);  //返回请求是否执行成功,即HTTP Code是否为2XX
       }
       //delete
       static async Task<bool> DeletePerson(HttpClient client)
       {
           return await client.DeleteAsync("api/Person/1") //向Person发送DELETE请求
                              .ContinueWith(x => x.Result.IsSuccessStatusCode); //返回请求是否执行成功,即HTTP Code是否为2XX
       }
}

This completes the call to this set of APIs. Isn’t it very simple and convenient? HTTPClient uses a fully asynchronous method and has good scalability.

OK, so far a set of simple Restful API and C# client calls have been completed, but this is just the beginning. Web API is a very powerful framework, and its extension points are very rich. These extensions It can provide a lot of help for our development.

The above is the detailed content of How to call webApi. 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: An Introduction to the Powerful Programming LanguageC# .NET: An Introduction to the Powerful Programming LanguageApr 22, 2025 am 12:04 AM

The combination of C# and .NET provides developers with a powerful programming environment. 1) C# supports polymorphism and asynchronous programming, 2) .NET provides cross-platform capabilities and concurrent processing mechanisms, which makes them widely used in desktop, web and mobile application development.

.NET Framework vs. C#: Decoding the Terminology.NET Framework vs. C#: Decoding the TerminologyApr 21, 2025 am 12:05 AM

.NETFramework is a software framework, and C# is a programming language. 1..NETFramework provides libraries and services, supporting desktop, web and mobile application development. 2.C# is designed for .NETFramework and supports modern programming functions. 3..NETFramework manages code execution through CLR, and the C# code is compiled into IL and runs by CLR. 4. Use .NETFramework to quickly develop applications, and C# provides advanced functions such as LINQ. 5. Common errors include type conversion and asynchronous programming deadlocks. VisualStudio tools are required for debugging.

Demystifying C# .NET: An Overview for BeginnersDemystifying C# .NET: An Overview for BeginnersApr 20, 2025 am 12:11 AM

C# is a modern, object-oriented programming language developed by Microsoft, and .NET is a development framework provided by Microsoft. C# combines the performance of C and the simplicity of Java, and is suitable for building various applications. The .NET framework supports multiple languages, provides garbage collection mechanisms, and simplifies memory management.

C# and the .NET Runtime: How They Work TogetherC# and the .NET Runtime: How They Work TogetherApr 19, 2025 am 12:04 AM

C# and .NET runtime work closely together to empower developers to efficient, powerful and cross-platform development capabilities. 1) C# is a type-safe and object-oriented programming language designed to integrate seamlessly with the .NET framework. 2) The .NET runtime manages the execution of C# code, provides garbage collection, type safety and other services, and ensures efficient and cross-platform operation.

C# .NET Development: A Beginner's Guide to Getting StartedC# .NET Development: A Beginner's Guide to Getting StartedApr 18, 2025 am 12:17 AM

To start C#.NET development, you need to: 1. Understand the basic knowledge of C# and the core concepts of the .NET framework; 2. Master the basic concepts of variables, data types, control structures, functions and classes; 3. Learn advanced features of C#, such as LINQ and asynchronous programming; 4. Be familiar with debugging techniques and performance optimization methods for common errors. With these steps, you can gradually penetrate the world of C#.NET and write efficient applications.

C# and .NET: Understanding the Relationship Between the TwoC# and .NET: Understanding the Relationship Between the TwoApr 17, 2025 am 12:07 AM

The relationship between C# and .NET is inseparable, but they are not the same thing. C# is a programming language, while .NET is a development platform. C# is used to write code, compile into .NET's intermediate language (IL), and executed by the .NET runtime (CLR).

The Continued Relevance of C# .NET: A Look at Current UsageThe Continued Relevance of C# .NET: A Look at Current UsageApr 16, 2025 am 12:07 AM

C#.NET is still important because it provides powerful tools and libraries that support multiple application development. 1) C# combines .NET framework to make development efficient and convenient. 2) C#'s type safety and garbage collection mechanism enhance its advantages. 3) .NET provides a cross-platform running environment and rich APIs, improving development flexibility.

From Web to Desktop: The Versatility of C# .NETFrom Web to Desktop: The Versatility of C# .NETApr 15, 2025 am 12:07 AM

C#.NETisversatileforbothwebanddesktopdevelopment.1)Forweb,useASP.NETfordynamicapplications.2)Fordesktop,employWindowsFormsorWPFforrichinterfaces.3)UseXamarinforcross-platformdevelopment,enablingcodesharingacrossWindows,macOS,Linux,andmobiledevices.

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

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment