目录
article
WebApiClient
WebApiClient
一款基于HttpClient封装,只需要定义c#接口并修饰相关特性,即可异步调用远程http接口的客户端库。
项目地址:https://github.com/dotnetcore/WebApiClient
以下摘自 GitHub 的 ReadMe
WebApiClient
1. Nuget 包
WebApiClient.JIT
PM> install-package WebApiClient.JIT
- 可以在项目中直接引用 WebApiClient.JIT.dll 就能使用;
- 不适用于不支持 JIT 技术的平台 (IOS、UWP);
- 接口要求为 public;
WebApiClient.AOT
PM> install-package WebApiClient.AOT
- 项目必须使用 nuget 安装 WebApiClient.AOT 才能正常使用;
- 没有 JIT,支持的平台广泛;
- 接口不要求为 public,可以嵌套在类里面;
2. Http 请求
接口的声明
[HttpHost("http://www.webapiclient.com")]
public interface IMyWebApi : IHttpApi
{
// GET webapi/user?account=laojiu
// Return 原始 string 内容
[HttpGet("/webapi/user")]
ITask<string> GetUserByAccountAsync(string account);
// POST webapi/user
// Body Account=laojiu&password=123456
// Return json 或 xml 内容
[HttpPost("/webapi/user")]
ITask<UserInfo> UpdateUserWithFormAsync([FormContent] UserInfo user);
}
public class UserInfo
{
public string Account { get; set; }
[AliasAs("password")]
public string Password { get; set; }
[IgnoreSerialized]
public string Email { get; set; }
}
接口的调用
var client = HttpApiClient.Create<IMyWebApi>();
var user = new UserInfo { Account = "laojiu", Password = "123456" };
var user1 = await client.GetUserByAccountAsync("laojiu");
var user2 = await client.UpdateUserWithFormAsync(user);