REST (Representational State Transfer) 是一种架构风格,用于设计网络应用程序的API。它基于HTTP协议,使用标准的HTTP方法(GET, POST, PUT, DELETE等)来操作资源。
在.NET中,你可以使用多种方式与REST API交互,包括:
using System;
using System.Net.Http;
using System.Threading.Tasks;
class Program
{
static readonly HttpClient client = new HttpClient();
static async Task Main(string[] args)
{
try
{
// GET请求示例
string responseBody = await client.GetStringAsync("https://api.example.com/users");
Console.WriteLine(responseBody);
// POST请求示例
var user = new { Name = "John Doe", Email = "john@example.com" };
var content = new StringContent(JsonSerializer.Serialize(user), Encoding.UTF8, "application/json");
HttpResponseMessage response = await client.PostAsync("https://api.example.com/users", content);
response.EnsureSuccessStatusCode();
string responseContent = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseContent);
}
catch(HttpRequestException e)
{
Console.WriteLine($"请求错误: {e.Message}");
}
}
}
// 在Startup.cs中配置
services.AddHttpClient("ExampleClient", client =>
{
client.BaseAddress = new Uri("https://api.example.com/");
client.DefaultRequestHeaders.Add("Accept", "application/json");
});
// 在控制器或服务中使用
public class UserService
{
private readonly IHttpClientFactory _clientFactory;
public UserService(IHttpClientFactory clientFactory)
{
_clientFactory = clientFactory;
}
public async Task<List<User>> GetUsersAsync()
{
var client = _clientFactory.CreateClient("ExampleClient");
var response = await client.GetAsync("users");
if(response.IsSuccessStatusCode)
{
return await response.Content.ReadAsAsync<List<User>>();
}
throw new Exception("获取用户失败");
}
}
using RestSharp;
var client = new RestClient("https://api.example.com");
var request = new RestRequest("users", Method.GET);
var response = client.Execute<List<User>>(request);
if(response.IsSuccessful)
{
var users = response.Data;
foreach(var user in users)
{
Console.WriteLine(user.Name);
}
}
else
{
Console.WriteLine($"错误: {response.ErrorMessage}");
}
问题:频繁创建和销毁HttpClient实例会导致端口耗尽。
解决方案:
问题:API返回的JSON与C#模型不匹配。
解决方案:
public class User
{
[JsonPropertyName("user_name")]
public string Name { get; set; }
[JsonPropertyName("user_email")]
public string Email { get; set; }
}
问题:API需要认证(如JWT, OAuth)。
解决方案:
client.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Bearer", "your_token_here");
问题:API响应慢导致超时。
解决方案:
client.Timeout = TimeSpan.FromSeconds(30);
问题:未正确处理API错误响应。
解决方案:
try
{
var response = await client.GetAsync("users");
response.EnsureSuccessStatusCode();
// 处理成功响应
}
catch(HttpRequestException ex) when (ex.StatusCode == HttpStatusCode.NotFound)
{
Console.WriteLine("资源未找到");
}
catch(HttpRequestException ex)
{
Console.WriteLine($"HTTP错误: {ex.Message}");
}
通过以上方法和实践,你可以在.NET应用程序中高效、可靠地使用REST API。
没有搜到相关的文章