应该是 .Net
目前最流行的Restful Api 客户端库
官方文档
dotnet add package RestSharp
或者 NuGet搜索 RestSharp
var client = new RestClient();
// client.AddDefaultParameter("foo", "bar"); 这样每个请求都自带这个参数 client.AddDefaultQueryParameter("foo", "bar");
var request = new RestRequest(new Uri("url?key1=value1&key2=value2"), RestSharp.Method.Get);
request.AddHeader("Content-Type", "application/json");
// 如果是QueryParams 参数直接拼接在url中即可
// request.AddBody(请求体对象); // 这样用在Post 请求体 application/json
// request.AddParameter("key", "value"); //这个一般用在 Post application/x-www-form-urlencoded,可以使用AddObject来代替AddParameter 把parameter包装在一个object里
// request.AddUrlSegment("id","123") 可以对url中的占位符进行赋值 url = /api/User/{id}
// request.AddCookie("foo", "bar"); 添加cookie
// request.AddFile 添加文件
// request.AddFile("File", "/C:/Users/HLT/Downloads/wind.png");
//request.AddFile("File", "/C:/Users/HLT/Downloads/凤凰传奇 - 全是爱.flac");
var response = await client.ExecuteAsync(request);
if (response.StatusCode == System.Net.HttpStatusCode.OK)
string result = response.Content;
上传文件:参数名称,文件路径/字节数组/等,
// Adds a file from disk
AddFile(parameterName, filePath, contentType);
// Adds an array of bytes
AddFile(parameterName, bytes, fileName, contentType);
// Adds a stream returned by the getFile function
AddFile(parameterName, getFile, fileName, contentType);
// 请求包装类
public class BaseRequest
{
public Method Method { get; set; }
public string Route { get; set; }
public string ContentType { get; set; } = "application/json";
public object Parameter { get; set; }
}
// 请求类
public class HttpRestClient
{
private readonly string apiUrl;
protected readonly RestClient client;
public HttpRestClient(string apiUrl)
{
this.apiUrl = apiUrl;
client = new RestClient();
}
public async Task<ApiResponse> ExecuteAsync(BaseRequest baseRequest)
{
var request = new RestRequest(new Uri(apiUrl + baseRequest.Route), baseRequest.Method);
request.AddHeader("Content-Type", baseRequest.ContentType);
if (baseRequest.Parameter != null)
//request.AddParameter("param", JsonConvert.SerializeObject(baseRequest.Parameter), ParameterType.RequestBody);
request.AddBody(baseRequest.Parameter);
var response = await client.ExecuteAsync(request);
if (response.StatusCode == System.Net.HttpStatusCode.OK)
return JsonConvert.DeserializeObject<ApiResponse>(response.Content);
else
return new ApiResponse()
{
Status = false,
Result = null,
Message = response.ErrorMessage
};
}
public async Task<ApiResponse<T>> ExecuteAsync<T>(BaseRequest baseRequest)
{
var request = new RestRequest(new Uri(apiUrl + baseRequest.Route), baseRequest.Method);
request.AddHeader("Content-Type", baseRequest.ContentType);
if (baseRequest.Parameter != null)
//request.AddParameter("param", JsonConvert.SerializeObject(baseRequest.Parameter), ParameterType.RequestBody);
request.AddBody(baseRequest.Parameter);
var response = await client.ExecuteAsync(request);
if (response.StatusCode == System.Net.HttpStatusCode.OK)
return JsonConvert.DeserializeObject<ApiResponse<T>>(response.Content);
else
return new ApiResponse<T>()
{
Status = false,
Message = response.ErrorMessage
};
}
}
// 基础请求动作分装
public interface IBaseService<TEntity> where TEntity : class
{
Task<ApiResponse<TEntity>> AddAsync(TEntity entity);
Task<ApiResponse<TEntity>> UpdateAsync(TEntity entity);
Task<ApiResponse> DeleteAsync(int id);
Task<ApiResponse<TEntity>> GetFirstOfDefaultAsync(int id);
Task<ApiResponse<PagedList<TEntity>>> GetAllAsync(QueryParameter parameter);
}
// 基本请求动作分装实现
public class BaseService<TEntity> : IBaseService<TEntity> where TEntity : class
{
private readonly HttpRestClient client;
private readonly string serviceName;
public BaseService(HttpRestClient client, string serviceName)
{
this.client = client;
this.serviceName = serviceName;
}
public async Task<ApiResponse<TEntity>> AddAsync(TEntity entity)
{
BaseRequest request = new BaseRequest();
request.Method = RestSharp.Method.Post;
request.Route = $"api/{serviceName}/Add";
request.Parameter = entity;
return await client.ExecuteAsync<TEntity>(request);
}
public async Task<ApiResponse> DeleteAsync(int id)
{
BaseRequest request = new BaseRequest();
request.Method = RestSharp.Method.Delete;
request.Route = $"api/{serviceName}/Delete?id={id}";
return await client.ExecuteAsync(request);
}
public async Task<ApiResponse<PagedList<TEntity>>> GetAllAsync(QueryParameter parameter)
{
BaseRequest request = new BaseRequest();
request.Method = RestSharp.Method.Get;
request.Route = $"api/{serviceName}/GetAll?pageIndex={parameter.PageIndex}" +
$"&pageSize={parameter.PageSize}" +
$"&search={parameter.Search}";
return await client.ExecuteAsync<PagedList<TEntity>>(request);
}
public async Task<ApiResponse<TEntity>> GetFirstOfDefaultAsync(int id)
{
BaseRequest request = new BaseRequest();
request.Method = RestSharp.Method.Get;
request.Route = $"api/{serviceName}/Get?id={id}";
return await client.ExecuteAsync<TEntity>(request);
}
public async Task<ApiResponse<TEntity>> UpdateAsync(TEntity entity)
{
BaseRequest request = new BaseRequest();
request.Method = RestSharp.Method.Post;
request.Route = $"api/{serviceName}/Update";
request.Parameter = entity;
return await client.ExecuteAsync<TEntity>(request);
}
}
在以上这几个类的基础上,我们只需要创建一个实例继承IBaseService和BaseService即可
public interface IToDoService:IBaseService<ToDoDto>
{
// 额外的接口
public Task<ApiResponse<PagedList<ToDoDto>>> GetAllFilterAsync(ToDoParameter param);
}
// 真正我们使用的类
public class ToDoService : BaseService<ToDoDto>, IToDoService
{
public ToDoService(HttpRestClient client) : base(client, "ToDo")
{
this.client = client;
}
private readonly HttpRestClient client;
public async Task<ApiResponse<PagedList<ToDoDto>>> GetAllFilterAsync(ToDoParameter param)
{
BaseRequest request = new BaseRequest();
request.Method = RestSharp.Method.Get;
request.Route = $"api/ToDo/GetAll?pageIndex={param.PageIndex}" +
$"&pageSize={param.PageSize}" +
$"&search={param.Search}" +
$"&Status={param.Status}";
return await client.ExecuteAsync<PagedList<ToDoDto>>(request);
}
}
public partial class App
{
protected override Window CreateShell()
{
return Container.Resolve<MainWindow>();
}
protected override void RegisterTypes(IContainerRegistry containerRegistry)
{
// 注册一个服务key 为 webUrl 为它创建实例传入构造参数
containerRegistry.GetContainer().Register<HttpRestClient>(made: Parameters.Of.Type<string>(serviceKey: "webUrl"));
containerRegistry.GetContainer().RegisterInstance(@"http://localhost:3333/", serviceKey: "webUrl");
containerRegistry.Register<IToDoService, ToDoService>();
containerRegistry.RegisterForNavigation<IndexView, IndexViewModel>();
containerRegistry.RegisterForNavigation<TodoView, TodoViewModel>();
containerRegistry.RegisterForNavigation<MemoView, MemoViewModel>();
containerRegistry.RegisterForNavigation<SettingsView, SettingsViewModel>();
containerRegistry.RegisterForNavigation<SkinView, SkinViewModel>();
containerRegistry.RegisterForNavigation<AbortView>();
}
}
重点在
将前面的 HttpRestClient 需要的构造函数进行注入,这样才可以将HttpRestClient 加入到 IOC
容器中
// 注册一个服务key 为 webUrl 为它创建实例传入构造参数
containerRegistry.GetContainer().Register<HttpRestClient>(made: Parameters.Of.Type<string>(serviceKey: "webUrl"));
containerRegistry.GetContainer().RegisterInstance(@"http://localhost:3333/", serviceKey: "webUrl");