maui-rest-api

在 .NET MAUI 应用中调用 REST API 的指南,涵盖使用 System.Text.Json 配置 HttpClient、依赖注入、服务接口/实现模式、完整 CRUD 操作(GET/POST/PUT/DELETE)、错误处理、平台明文流量配置以及 async/await 最佳实践。

仓库最近推送
GitHub Stars
181
Forks
21
Issues / PRs
1

安装方式

先用 Prompt 核对来源与依赖。也可下载安装包。

用 AI 助手安装

复制提示词,让助手先核对固定版本和依赖。

查看 Prompt收起 Prompt
先检查当前 Agent 是否已安装 SkillPI Skill Finder。如果尚未安装,请按官方仓库的说明安装并启用:https://github.com/Findskills/skillpi。然后使用 Skill Finder 打开此 SkillPI 详情页并定位 "maui-rest-api":https://skillpi.com/zh/skills/deepskill-7b5818fb36dc758163ba2420da55fc4872150b31bcff93515687c83820c076b1。安装前核对上游来源和版本:https://github.com/davidortinau/maui-skills。来源不一致时停止并说明差异。核对通过后,用 Skill Finder 安装目标 Skill,并报告安装路径和来源版本。

来源与配置

github.com

配置方式待核实

请查看原始来源中的适用工具、依赖和权限要求。

安装实测待补充

在 .NET MAUI 应用中调用 REST API 的指南,涵盖使用 System.Text.Json 配置 HttpClient、依赖注入、服务接口/实现模式、完整 CRUD 操作(GET/POST/PUT/DELETE)、错误处理、平台明文流量配置以及 async/await 最佳实践。

0 下载

介绍来源: third_party · davidortinau · 0.0.1 参考来源

SkillPi 解读

能完成的任务
翻译待完成,请参阅来源文档。
实测状态
未测试

文件浏览

在原站浏览文件 ↗

原始 SKILL.md

打开原文 ↗
Frontmatter
name: maui-rest-api
description: >
  Guidance for consuming REST APIs in .NET MAUI apps. Covers HttpClient setup
  with System.Text.Json, DI registration, service interface/implementation
  pattern, full CRUD operations (GET, POST, PUT, DELETE), error handling,
  platform-specific clear-text traffic configuration, and async/await best practices.
  USE FOR: "REST API", "HttpClient", "call API", "GET request", "POST request",
  "API service", "JSON deserialization", "CRUD operations", "clear-text traffic",
  "consume API MAUI".
  DO NOT USE FOR: Aspire service discovery (use maui-aspire), authentication token handling
  (use maui-authentication), or local database storage (use maui-sqlite-database).

REST API Consumption — Gotchas & Best Practices

Common Mistakes

1. Creating HttpClient per request

// ❌ Creates socket exhaustion — each instance opens a new connection
public async Task<List<Item>> GetItemsAsync()
{
    using var client = new HttpClient();
    var response = await client.GetAsync("https://api.example.com/items");
    // ...
}

// ✅ Register once in DI, inject everywhere
builder.Services.AddSingleton(sp => new HttpClient
{
    BaseAddress = new Uri("https://api.example.com")
});

2. Blocking with .Result or .Wait()

// ❌ Deadlocks on the UI thread
var items = _apiService.GetItemsAsync().Result;

// ✅ Always use async/await
var items = await _apiService.GetItemsAsync();

3. Deserializing before checking status

// ❌ Tries to deserialize error HTML/JSON as your model
var content = await response.Content.ReadAsStringAsync();
var items = JsonSerializer.Deserialize<List<Item>>(content, _jsonOptions);

// ✅ Check status first
response.EnsureSuccessStatusCode();
var content = await response.Content.ReadAsStringAsync();
var items = JsonSerializer.Deserialize<List<Item>>(content, _jsonOptions) ?? [];

4. Hardcoding BaseAddress in service methods

// ❌ Absolute URIs in every method — hard to change, easy to typo
await _httpClient.GetAsync("https://api.example.com/api/items");

// ✅ Set BaseAddress in DI, use relative URIs in methods
await _httpClient.GetAsync("api/items");

5. Missing error handling for network failures

// ❌ Crashes on network timeout, DNS failure, etc.
var items = await _apiService.GetItemsAsync();

// ✅ Catch both network and deserialization errors
try
{
    var items = await _apiService.GetItemsAsync();
}
catch (HttpRequestException ex) { /* network or HTTP error */ }
catch (JsonException ex) { /* malformed response */ }

Platform Pitfalls

⚠️ Clear-text HTTP blocked on emulators/simulators

Local dev servers on http:// are blocked by default. Configure exceptions:

  • Android: needs network_security_config.xml with cleartextTrafficPermitted="true" for 10.0.2.2
  • iOS/Mac Catalyst: needs NSAllowsLocalNetworking in Info.plist

⚠️ Android emulator uses 10.0.2.2 for localhost

The Android emulator maps 10.0.2.2 to the host machine. localhost refers to the emulator itself.

// ❌ On Android emulator, this hits the emulator, not your dev machine
new Uri("http://localhost:5000")

// ✅ Use the emulator's host loopback address
new Uri("http://10.0.2.2:5000")

iOS simulators use localhost directly.

⚠️ Inconsistent JSON casing

APIs typically use camelCase; C# properties are PascalCase. Without JsonSerializerOptions, deserialization silently returns default values.

// ❌ Properties stay null/default — no error thrown
JsonSerializer.Deserialize<Item>(content);

// ✅ Configure casing policy
private static readonly JsonSerializerOptions _jsonOptions = new()
{
    PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
    PropertyNameCaseInsensitive = true
};

Decision Framework

Scenario Error handling approach
Failure is unexpected (auth'd endpoints) EnsureSuccessStatusCode() — throws HttpRequestException
Need to branch on status codes Check IsSuccessStatusCode or response.StatusCode
Network may be unreliable (mobile) Wrap in try/catch for HttpRequestException
Response format may vary Also catch JsonException

Checklist

  • [ ] HttpClient registered as singleton or via IHttpClientFactory — never created per-request
  • [ ] BaseAddress set in DI; service methods use relative URIs
  • [ ] JsonSerializerOptions with CamelCase policy applied consistently
  • [ ] IsSuccessStatusCode or EnsureSuccessStatusCode() checked before deserializing
  • [ ] try/catch for HttpRequestException and JsonException in ViewModel calls
  • [ ] All API calls use async/await — no .Result or .Wait()
  • [ ] Service interface pattern used so ViewModels depend on abstractions
  • [ ] Android clear-text config for local dev (10.0.2.2)
  • [ ] iOS NSAllowsLocalNetworking for local dev

当前收录版本

0.0.1

核对来源版本 ↗

质量评测

满分100 · 来自 SkillPi LAB 实验室的评测报告。

场景价值92/100

亮点

  • 提供.NET MAUI应用中调用REST API的完整指南
  • 涵盖HttpClient配置、依赖注入、CRUD操作、错误处理等核心内容
  • 包含平台特定的明文流量配置和async/await最佳实践
触发精准95/100

亮点

  • 触发词定义清晰完整,覆盖多种相关场景
  • 明确排除了易混淆的相邻领域(如认证、本地数据库)
结构规范85/100

待提升项

  • 缺少显式的'When to Use'章节 原报告严重程度:轻微

    虽然在frontmatter中描述了适用场景,但正文缺少独立的'When to Use'章节

    改进建议:建议在正文开头添加独立的'When to Use'章节,与'DO NOT USE FOR'形成呼应

  • 缺少端到端的完整项目示例结构 原报告严重程度:轻微

    提供了代码片段和最佳实践,但缺少完整的项目结构示例

    改进建议:建议添加一个完整的示例项目结构,展示服务接口、实现、ViewModel集成等

亮点

  • 结构清晰,分章节组织内容
  • 每个常见错误都提供了错误示例和正确解决方案
  • 包含决策框架和检查清单,便于实践应用
执行可靠95/100

亮点

  • 代码示例准确,遵循.NET MAUI最佳实践
  • 错误处理建议全面,覆盖网络异常和反序列化异常
  • 平台特定配置说明详细,可直接应用于实际开发
证据可验 (前四项均值)92/100

取前四项原始分值的算术平均,四舍五入取整。可通过收录报告核对各项评分与说明,运行记录需单独查证。

正文静态检测

100 / 100 · skillpi-20261123-no-r3-v1

正文未命中当前规则。

分数仅反映正文中的规则命中,供使用前参考。附件与运行行为不在此评分范围内。

权限与使用前检查

根据当前主文档自动整理,命中内容可能是示例或防护说明;不是实际权限声明,也未覆盖附件、外部依赖或运行行为。

未从主文档识别到上述常见操作,不能据此判断无需权限或没有风险。

文档引用的域名或地址

这些地址可能用于文档链接或示例,不是已批准的联网清单。使用前核对实际目的地及发送的数据。

  • 10.0.2.2
  • api.example.com
  • localhost

本站展示提示不会授予权限。涉及文件改动、密钥、外部发送或费用时,仍由你使用的工具按需确认。

安全评级与访问范围

safe · 静态证据核验,不代表运行安全保证。

使用前请由宿主核对并授权实际文件读写、外部服务和联网目的地;本站的核验不会授予任何运行权限。