C# RESTful完整使用實戰(zhàn)示例
更新時間:2025年12月04日 09:07:43 作者:wangnaisheng
RESTful是一種輕量級、跨平臺的Web服務(wù)架構(gòu)風(fēng)格,C# 中使用 RESTful API主要涉及客戶端調(diào)用和服務(wù)器端實現(xiàn)兩個方面,接下來通過本文介紹C# RESTful完整使用實戰(zhàn)示例,感興趣的朋友一起看看吧
一、RESTful基礎(chǔ)
RESTful是一種輕量級、跨平臺的Web服務(wù)架構(gòu)風(fēng)格,它的核心原則是:
- 資源唯一標(biāo)識:每個資源有唯一的URL
- 無狀態(tài)操作:服務(wù)器不保存客戶端狀態(tài)
- 統(tǒng)一接口:用標(biāo)準(zhǔn)HTTP方法操作資源
| HTTP方法 | 操作 | 冪等 | 安全 |
|---|---|---|---|
| GET | 查詢 | 是 | 是 |
| POST | 新增 | 否 | 否 |
| PUT | 更新 | 是 | 否 |
| DELETE | 刪除 | 是 | 否 |
RESTful vs 傳統(tǒng)API:
- 傳統(tǒng):
/user/query/1 - RESTful:
/user/1
二、調(diào)用RESTful API的通用流程
// 1. 獲取數(shù)據(jù) - HttpClient最佳實踐
using var httpClient = new HttpClient();
var response = await httpClient.GetAsync("https://api.example.com/data");
var jsonString = await response.Content.ReadAsStringAsync();
// 2. 解析JSON - 兩種常用方式
// 方式一:動態(tài)解析(快速提取少量字段)
var jsonDoc = JsonDocument.Parse(jsonString);
string name = jsonDoc.RootElement.GetProperty("user").GetProperty("name").GetString();
// 方式二:強(qiáng)類型解析(推薦!)
public class User {
public string Name { get; set; }
public int Age { get; set; }
public DateTime RegisterDate { get; set; }
}
var user = JsonSerializer.Deserialize<User>(jsonString, new JsonSerializerOptions {
PropertyNameCaseInsensitive = true // 忽略大小寫
});
// 3. 使用解析后的數(shù)據(jù)
Console.WriteLine($"歡迎,{user.Name}!您已注冊于{user.RegisterDate:yyyy-MM-dd}");三、JSON解析的實用技巧
3.1 推薦方案
使用System.Text.Json(.NET Core 3.0+)
優(yōu)勢:
- 微軟原生,性能更好
- 編譯時檢查 + 智能提示 + 高可維護(hù)性
- 支持異步操作
3.2 常見坑點及解決方案
| 問題 | 解決方案 | 代碼示例 |
|---|---|---|
| 字段大小寫不一致 | PropertyNameCaseInsensitive = true | new JsonSerializerOptions { PropertyNameCaseInsensitive = true } |
| 日期格式問題 | 添加日期轉(zhuǎn)換器 | options.Converters.Add(new DateTimeConverter("yyyy-MM-dd")); |
| JSON中有注釋 | 忽略注釋 | options.ReadCommentHandling = JsonCommentHandling.Skip; |
| 空字段導(dǎo)致異常 | 設(shè)置默認(rèn)值 | public string Name { get; set; } = string.Empty; |
四、完整實戰(zhàn)示例
using System;
using System.Net.Http;
using System.Text.Json;
using System.Threading.Tasks;
public class WeatherApiService
{
public async Task<WeatherData> GetWeatherAsync(string location)
{
using var httpClient = new HttpClient();
// 獲取天氣數(shù)據(jù)
var response = await httpClient.GetAsync(
$"https://api.weather.com/v3?location={location}");
response.EnsureSuccessStatusCode();
var json = await response.Content.ReadAsStringAsync();
// 強(qiáng)類型解析(推薦方式)
return JsonSerializer.Deserialize<WeatherData>(json, new JsonSerializerOptions {
PropertyNameCaseInsensitive = true,
NumberHandling = JsonNumberHandling.AllowReadingFromString
});
}
}
public class WeatherData
{
public string City { get; set; }
public string Condition { get; set; }
public int Temperature { get; set; }
public DateTime ForecastDate { get; set; }
}五、為什么推薦System.Text.Json?
- 性能更好:比Newtonsoft.Json快約20-30%
- 原生集成:.NET Core 3.0+默認(rèn)包含
- 安全:不依賴第三方庫,減少安全風(fēng)險
- 現(xiàn)代化:支持最新的JSON特性
六、進(jìn)階建議
- 創(chuàng)建通用API服務(wù)類:把HttpClient封裝起來,避免重復(fù)代碼
- 處理錯誤:添加try-catch塊處理網(wǎng)絡(luò)異常
- 緩存:對頻繁請求的API添加緩存機(jī)制
- 異步:始終使用異步方法,提升應(yīng)用性能
七、處理JSON嵌套復(fù)雜結(jié)構(gòu)
三步搞定嵌套JSON處理(推薦System.Text.Json)
7.1 第一步:定義強(qiáng)類型模型(關(guān)鍵?。?/h3>
// 定義嵌套結(jié)構(gòu)
public class ApiResponse
{
public string Status { get; set; }
public Data Data { get; set; }
}
public class Data
{
public List<User> Users { get; set; }
public Meta Meta { get; set; }
}
public class User
{
public int Id { get; set; }
public string Name { get; set; }
public Address Address { get; set; }
}
public class Address
{
public string Street { get; set; }
public string City { get; set; }
public string ZipCode { get; set; }
}
public class Meta
{
public int TotalCount { get; set; }
public int Page { get; set; }
public int PageSize { get; set; }
}
// 定義嵌套結(jié)構(gòu)
public class ApiResponse
{
public string Status { get; set; }
public Data Data { get; set; }
}
public class Data
{
public List<User> Users { get; set; }
public Meta Meta { get; set; }
}
public class User
{
public int Id { get; set; }
public string Name { get; set; }
public Address Address { get; set; }
}
public class Address
{
public string Street { get; set; }
public string City { get; set; }
public string ZipCode { get; set; }
}
public class Meta
{
public int TotalCount { get; set; }
public int Page { get; set; }
public int PageSize { get; set; }
}7.2 第二步:解析嵌套JSON(一行代碼搞定?。?/h3>
// 獲取API返回的JSON字符串
string json = await httpClient.GetStringAsync("https://api.example.com/data");
// 一行代碼解析嵌套結(jié)構(gòu)(這才是真正的"快速"?。?
var response = JsonSerializer.Deserialize<ApiResponse>(json, new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true, // 忽略大小寫
NumberHandling = JsonNumberHandling.AllowReadingFromString // 處理數(shù)字字符串
});
// 獲取API返回的JSON字符串
string json = await httpClient.GetStringAsync("https://api.example.com/data");
// 一行代碼解析嵌套結(jié)構(gòu)(這才是真正的"快速"?。?
var response = JsonSerializer.Deserialize<ApiResponse>(json, new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true, // 忽略大小寫
NumberHandling = JsonNumberHandling.AllowReadingFromString // 處理數(shù)字字符串
});7.3 第三步:安全訪問嵌套數(shù)據(jù)
// 安全訪問嵌套數(shù)據(jù)
if (response != null && response.Data != null && response.Data.Users != null)
{
foreach (var user in response.Data.Users)
{
Console.WriteLine($"用戶: {user.Name}, 城市: {user.Address.City}");
}
// 也可以直接訪問
Console.WriteLine($"總用戶數(shù): {response.Data.Meta.TotalCount}");
}- 強(qiáng)類型安全:編譯時檢查,不會等到運行時才發(fā)現(xiàn)錯誤
- 代碼可讀性高:一目了然,不需要寫一堆
doc["data"]["users"][0]["address"]["city"] - 性能更好:比Newtonsoft.Json快20-30%(.NET Core 3.0+)
- 自動處理嵌套:不需要手動遍歷每一層
八、實用技巧:處理常見嵌套問題
8.1 嵌套層級太深,字段可能為空
// 安全訪問嵌套字段(避免NullReferenceException)
var city = response?.Data?.Users?[0]?.Address?.City ?? "N/A";
Console.WriteLine($"城市: {city}");8.2 JSON字段名大小寫不一致
new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true // 關(guān)鍵!忽略大小寫
}8.3 嵌套結(jié)構(gòu)中可能有額外字段
// 忽略未知字段
new JsonSerializerOptions
{
IgnoreUnknown = true
}8.4 處理嵌套數(shù)組
// 獲取所有用戶的姓名
var userNames = response.Data.Users
.Where(u => u.Id > 100)
.Select(u => u.Name)
.ToList();一個真實案例:處理天氣API的嵌套JSON
public class WeatherResponse
{
public CurrentWeather Current { get; set; }
public Forecast Forecast { get; set; }
}
public class CurrentWeather
{
public string City { get; set; }
public int Temperature { get; set; }
public string Condition { get; set; }
}
public class Forecast
{
public List<DailyForecast> Days { get; set; }
}
public class DailyForecast
{
public DateTime Date { get; set; }
public int HighTemp { get; set; }
public int LowTemp { get; set; }
}
// 使用方式
var weather = JsonSerializer.Deserialize<WeatherResponse>(json);
Console.WriteLine($"當(dāng)前城市: {weather.Current.City}, 溫度: {weather.Current.Temperature}°C");
Console.WriteLine($"明天最高溫: {weather.Forecast.Days[0].HighTemp}°C");到此這篇關(guān)于C# RESTful完整使用實戰(zhàn)示例的文章就介紹到這了,更多相關(guān)c# restful使用內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
您可能感興趣的文章:
相關(guān)文章
C#實現(xiàn)Stream與byte[]之間的轉(zhuǎn)換實例教程
這篇文章主要介紹了C#實現(xiàn)Stream與byte[]之間的轉(zhuǎn)換方法,具體講解了二進(jìn)制轉(zhuǎn)換成圖片、byte[]與string的轉(zhuǎn)換、Stream 和 byte[] 之間的轉(zhuǎn)換、Stream 和 文件之間的轉(zhuǎn)換、從文件讀取 Stream以及Bitmap 轉(zhuǎn)化為 Byte[]等,需要的朋友可以參考下2014-09-09
C# WPF實現(xiàn)讀寫CAN數(shù)據(jù)
這篇文章主要介紹了C# WPF實現(xiàn)讀寫CAN數(shù)據(jù),文中通過代碼示例給大家講解的非常詳細(xì),對大家的學(xué)習(xí)或工作有一定的幫助,需要的朋友可以參考下2024-06-06

