feat: add 客户端
This commit is contained in:
88
PetWashControl/Services/ApiService.cs
Normal file
88
PetWashControl/Services/ApiService.cs
Normal file
@@ -0,0 +1,88 @@
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Json;
|
||||
using PetWashControl.Models;
|
||||
|
||||
namespace PetWashControl.Services;
|
||||
|
||||
public class ApiService
|
||||
{
|
||||
private readonly HttpClient _httpClient;
|
||||
private readonly ConfigurationService _config;
|
||||
|
||||
public ApiService(ConfigurationService? config = null)
|
||||
{
|
||||
_config = config ?? new ConfigurationService();
|
||||
_httpClient = new HttpClient
|
||||
{
|
||||
BaseAddress = new Uri(_config.ApiBaseUrl),
|
||||
Timeout = TimeSpan.FromSeconds(30)
|
||||
};
|
||||
}
|
||||
|
||||
public async Task<List<Package>> GetPackagesAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
return await _httpClient.GetFromJsonAsync<List<Package>>("api/packages")
|
||||
?? new List<Package>();
|
||||
}
|
||||
catch (HttpRequestException ex)
|
||||
{
|
||||
throw new Exception($"无法连接到服务器: {ex.Message}", ex);
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<Order?> CreateOrderAsync(int packageId)
|
||||
{
|
||||
try
|
||||
{
|
||||
var response = await _httpClient.PostAsJsonAsync("api/orders", new { packageId });
|
||||
response.EnsureSuccessStatusCode();
|
||||
return await response.Content.ReadFromJsonAsync<Order>();
|
||||
}
|
||||
catch (HttpRequestException ex)
|
||||
{
|
||||
throw new Exception($"创建订单失败: {ex.Message}", ex);
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<Order?> ConfirmPaymentAsync(int orderId)
|
||||
{
|
||||
try
|
||||
{
|
||||
var response = await _httpClient.PostAsync($"api/orders/{orderId}/payment", null);
|
||||
response.EnsureSuccessStatusCode();
|
||||
return await response.Content.ReadFromJsonAsync<Order>();
|
||||
}
|
||||
catch (HttpRequestException ex)
|
||||
{
|
||||
throw new Exception($"确认支付失败: {ex.Message}", ex);
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<Order?> GetOrderAsync(int orderId)
|
||||
{
|
||||
try
|
||||
{
|
||||
return await _httpClient.GetFromJsonAsync<Order>($"api/orders/{orderId}");
|
||||
}
|
||||
catch (HttpRequestException ex)
|
||||
{
|
||||
throw new Exception($"获取订单失败: {ex.Message}", ex);
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<Order?> UpdateOrderStatusAsync(int orderId, OrderStatus status)
|
||||
{
|
||||
try
|
||||
{
|
||||
var response = await _httpClient.PutAsJsonAsync($"api/orders/{orderId}/status", new { status });
|
||||
response.EnsureSuccessStatusCode();
|
||||
return await response.Content.ReadFromJsonAsync<Order>();
|
||||
}
|
||||
catch (HttpRequestException ex)
|
||||
{
|
||||
throw new Exception($"更新订单状态失败: {ex.Message}", ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user