最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

C# RESTful完整使用實(shí)戰(zhàn)示例

 更新時間:2025年12月04日 09:07:43   作者:wangnaisheng  
RESTful是一種輕量級、跨平臺的Web服務(wù)架構(gòu)風(fēng)格,C# 中使用 RESTful API主要涉及客戶端調(diào)用和服務(wù)器端實(shí)現(xiàn)兩個方面,接下來通過本文介紹C# RESTful完整使用實(shí)戰(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最佳實(shí)踐
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解析的實(shí)用技巧

3.1 推薦方案

使用System.Text.Json(.NET Core 3.0+)

優(yōu)勢

  • 微軟原生,性能更好
  • 編譯時檢查 + 智能提示 + 高可維護(hù)性
  • 支持異步操作

3.2 常見坑點(diǎn)及解決方案

問題解決方案代碼示例
字段大小寫不一致PropertyNameCaseInsensitive = truenew 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;

四、完整實(shí)戰(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?

  1. 性能更好:比Newtonsoft.Json快約20-30%
  2. 原生集成:.NET Core 3.0+默認(rèn)包含
  3. 安全:不依賴第三方庫,減少安全風(fēng)險
  4. 現(xiàn)代化:支持最新的JSON特性

六、進(jìn)階建議

  1. 創(chuàng)建通用API服務(wù)類:把HttpClient封裝起來,避免重復(fù)代碼
  2. 處理錯誤:添加try-catch塊處理網(wǎng)絡(luò)異常
  3. 緩存:對頻繁請求的API添加緩存機(jī)制
  4. 異步:始終使用異步方法,提升應(yīng)用性能

七、處理JSON嵌套復(fù)雜結(jié)構(gòu)

三步搞定嵌套JSON處理(推薦System.Text.Json)

7.1 第一步:定義強(qiáng)類型模型(關(guān)鍵!)

// 定義嵌套結(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ù)字字符串
});

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)類型安全:編譯時檢查,不會等到運(yùn)行時才發(fā)現(xiàn)錯誤
  • 代碼可讀性高:一目了然,不需要寫一堆doc["data"]["users"][0]["address"]["city"]
  • 性能更好:比Newtonsoft.Json快20-30%(.NET Core 3.0+)
  • 自動處理嵌套:不需要手動遍歷每一層

八、實(shí)用技巧:處理常見嵌套問題

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();

一個真實(shí)案例:處理天氣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完整使用實(shí)戰(zhàn)示例的文章就介紹到這了,更多相關(guān)c# restful使用內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

您可能感興趣的文章:

相關(guān)文章

  • C# 創(chuàng)建報表過程詳解

    C# 創(chuàng)建報表過程詳解

    本文給大家介紹的是使用vs2012 c#創(chuàng)建報表的全部過程的記錄,十分的詳細(xì),有需要的小伙伴可以參考下。
    2015-06-06
  • 基于C#實(shí)現(xiàn)一維碼和二維碼打印功能

    基于C#實(shí)現(xiàn)一維碼和二維碼打印功能

    本文介紹了基于C#的條碼打印程序的設(shè)計與實(shí)現(xiàn),包括技術(shù)選型、核心功能、系統(tǒng)架構(gòu)、參數(shù)配置、工程實(shí)踐、擴(kuò)展功能、調(diào)試測試及部署建議,需要的朋友可以參考下
    2025-12-12
  • c# 線性回歸和多項式擬合示例詳解

    c# 線性回歸和多項式擬合示例詳解

    線性回歸與多項式擬合是兩種常用的回歸分析方法,線性回歸模型簡單,易于計算,但只適用于線性關(guān)系的數(shù)據(jù),多項式擬合能處理非線性數(shù)據(jù),模型更復(fù)雜,擬合度更高,但容易產(chǎn)生過擬合問題,計算成本較高,適用場景不同,線性回歸適合線性數(shù)據(jù),多項式擬合適合非線性數(shù)據(jù)
    2024-10-10
  • C#實(shí)現(xiàn)六大設(shè)計原則之接口隔離原則

    C#實(shí)現(xiàn)六大設(shè)計原則之接口隔離原則

    這篇文章介紹了C#實(shí)現(xiàn)六大設(shè)計原則之接口隔離原則的方法,文中通過示例代碼介紹的非常詳細(xì)。對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2022-02-02
  • C#委托初級使用的實(shí)例代碼

    C#委托初級使用的實(shí)例代碼

    這篇代碼介紹了C#中委托的初級使用實(shí)例,有需要的朋友可以參考一下
    2013-06-06
  • C#實(shí)現(xiàn)Stream與byte[]之間的轉(zhuǎn)換實(shí)例教程

    C#實(shí)現(xiàn)Stream與byte[]之間的轉(zhuǎn)換實(shí)例教程

    這篇文章主要介紹了C#實(shí)現(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#如何綁定多個按鈕到同一個事件

    C#如何綁定多個按鈕到同一個事件

    這篇文章主要介紹了C#如何綁定多個按鈕到同一個事件,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-04-04
  • C# WPF實(shí)現(xiàn)讀寫CAN數(shù)據(jù)

    C# WPF實(shí)現(xiàn)讀寫CAN數(shù)據(jù)

    這篇文章主要介紹了C# WPF實(shí)現(xiàn)讀寫CAN數(shù)據(jù),文中通過代碼示例給大家講解的非常詳細(xì),對大家的學(xué)習(xí)或工作有一定的幫助,需要的朋友可以參考下
    2024-06-06
  • c# 引用Nlog插件的步驟

    c# 引用Nlog插件的步驟

    這篇文章主要介紹了c# 引用Nlog插件的步驟,幫助大家更好的理解和學(xué)習(xí)使用c#,感興趣的朋友可以了解下
    2021-04-04
  • 關(guān)于C#中的字體別名問題

    關(guān)于C#中的字體別名問題

    在C#中使用Graphics對象的DrawString方法繪制文本時,可以通過設(shè)置TextRenderingHint屬性來控制字體混疊效果,對于14號或更大的字體,建議使用AntiAliasGridFit;對于8到14點(diǎn)之間的字體,建議使用AntiAlias;對于小于8點(diǎn)的字體,建議使用ClearTypeGridFit
    2025-01-01

最新評論

吴川市| 清河县| 巍山| 措美县| 龙岩市| 金沙县| 斗六市| 松溪县| 即墨市| 宝丰县| 寿阳县| 蛟河市| 孝义市| 吉林市| 浑源县| 梨树县| 和顺县| 读书| 车致| 青铜峡市| 抚顺市| 东乌珠穆沁旗| 乌兰浩特市| 临海市| 苍南县| 历史| 沾益县| 始兴县| 云阳县| 蒙阴县| 通许县| 宁化县| 巴里| 萨嘎县| 金昌市| 谢通门县| 神农架林区| 乌拉特前旗| 吉林省| 江油市| 抚宁县|