1、在WPF项目中添加Nuget包,搜索RestSharp安装
2、新建Service文件夹,新建基础通用请求类BaseRequest.cs
public class BaseRequest{public Method Method { get; set; }public string Route { get; set; }public string ContenType { get; set; } = "application/json";public string Parameter { get; set; }}
3、在WPFProjectShared项目下新增类WebApiResponse.cs接收api返回信息
public class WebApiResponse{public string Message { get; set; }public bool Status { get; set; }public object Result { get; set; }}public class WebApiResponse<T>{public string Message { get; set; }public bool Status { get; set; }public T Result { get; set; }}
4、添加httpclient请求帮助类
public class HttpRestClient{public readonly string apiUrl;protected readonly RestClient client;public HttpRestClient(string apiUrl){this.apiUrl = apiUrl;client = new RestClient();}public async Task<WebApiResponse> ExecuteAsync(BaseRequest baseRequest){var request = new RestRequest(baseRequest.Method);request.AddHeader("Content-Type", baseRequest.ContenType.ToString());if (baseRequest.Parameter != null)request.AddParameter("param", JsonConvert.SerializeObject(baseRequest.Parameter), ParameterType.RequestBody);client.BaseUrl = new Uri(apiUrl + baseRequest.Route);var response = await client.ExecuteAsync(request);if (response.StatusCode == System.Net.HttpStatusCode.OK)return JsonConvert.DeserializeObject<WebApiResponse>(response.Content);elsereturn new WebApiResponse(){Status = false,Result = null,Message = response.ErrorMessage};}public async Task<WebApiResponse<T>> ExecuteAsync<T>(BaseRequest baseRequest){var request = new RestRequest(baseRequest.Method);request.AddHeader("Content-Type", baseRequest.ContenType);if (baseRequest.Parameter != null)request.AddParameter("param", JsonConvert.SerializeObject(baseRequest.Parameter), ParameterType.RequestBody);client.BaseUrl = new Uri(apiUrl + baseRequest.Route);var response = await client.ExecuteAsync(request);if (response.StatusCode == System.Net.HttpStatusCode.OK)return JsonConvert.DeserializeObject<WebApiResponse<T>>(response.Content);elsereturn new WebApiResponse<T>(){Status = false,Message = response.ErrorMessage};}}
5、新增接口IBaseService,添加增删改查方法
public interface IBaseService<TEntity> where TEntity : class{Task<WebApiResponse<TEntity>> AddAsync(TEntity entity);Task<WebApiResponse<TEntity>> UpdateAsync(TEntity entity);Task<WebApiResponse> DeleteAsync(int id);Task<WebApiResponse<TEntity>> GetFirstOfDefaultAsync(int id);Task<WebApiResponse<PagedList<TEntity>>> GetAllPageListAsync(QueryParameter parameter);}
6、实现接口BaseService
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<WebApiResponse<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<WebApiResponse> 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<WebApiResponse<PagedList<TEntity>>> GetAllPageListAsync(QueryParameter parameter){BaseRequest request = new BaseRequest();request.Method = RestSharp.Method.GET;request.Route = $"api/{serviceName}/GetAllPageListToDo?pageIndex={parameter.PageIndex}" + $"&pageSize={parameter.PageSize}" + $"&search={parameter.Search}";return await client.ExecuteAsync<PagedList<TEntity>>(request);}public async Task<WebApiResponse<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<WebApiResponse<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);}}
7、新增IToDoService接口,继承IBaseService接口
public interface IToDoService:IBaseService<ToDoDto>{}
8、新增ToDoService类,继承BaseService类和接口IToDoService
public class ToDoService : BaseService<ToDoDto>, IToDoService{public ToDoService(HttpRestClient client) : base(client, "ToDo"){}}
9、在客户端App.xaml中注册httprestclient、注册默认服务的地址、注册服务
/// <summary>/// Interaction logic for App.xaml/// </summary>public partial class App : PrismApplication{protected override Window CreateShell(){return Container.Resolve<MainView>();}protected override void RegisterTypes(IContainerRegistry containerRegistry){//注册httprestclientcontainerRegistry.GetContainer().Register<HttpRestClient>(made: Parameters.Of.Type<string>(serviceKey: "webUrl"));//注册默认服务的地址containerRegistry.GetContainer().RegisterInstance(@"http://localhost:5000/", serviceKey: "webUrl");//注册服务containerRegistry.Register<IToDoService, ToDoService>();containerRegistry.RegisterForNavigation<IndexView, IndexViewModel>();containerRegistry.RegisterForNavigation<MemoView, MemoViewModel>();containerRegistry.RegisterForNavigation<SettingsView, SettingsViewModel>();containerRegistry.RegisterForNavigation<ToDoView, ToDoViewModel>();containerRegistry.RegisterForNavigation<SkinView, SkinViewModel>();containerRegistry.RegisterForNavigation<AboutView, AboutViewModel>();containerRegistry.RegisterForNavigation<SystemSettingsView, SystemSettingsViewModel>();}}
10、修改ToDoViewModel的代码,添加ToDoService服务,修改CreateToDoList 代码
private readonly IToDoService toDoService;public ToDoViewModel(IToDoService toDoService){ToDoDtos = new ObservableCollection<ToDoDto>();AddCommand = new DelegateCommand(Add);this.toDoService = toDoService;CreateToDoList();}private async void CreateToDoList(){var todoResult = await toDoService.GetAllPageListAsync(new WPFProjectShared.Parameters.QueryParameter{PageIndex = 0,PageSize = 100});if (todoResult.Status){toDoDtos.Clear();foreach (var item in todoResult.Result.Items){toDoDtos.Add(item);}}}
11、右击解决方案-属性,设置多项目同时启动
12、F5启动项目,点击【待办事项】,显示了待办事项的列表这和webapi中返回的待办事项Json数据一样。
{"message": null,"status": true,"result": {"pageIndex": 0,"pageSize": 100,"totalCount": 5,"totalPages": 1,"indexFrom": 0,"items": [{"title": "测试新增待办事项","content": "测试新增待办事项","status": 0,"id": 2009,"createDate": "2023-11-22T15:48:50.8859172","updateDate": "2023-11-22T15:48:50.8861276"},{"title": "测试api","content": "测试api","status": 1,"id": 1009,"createDate": "2023-08-29T16:41:44.93631","updateDate": "2023-11-22T15:20:45.5035496"},{"title": "测试AutoMapper","content": "AutoMapper","status": 1,"id": 1008,"createDate": "2023-08-09T05:58:46.957","updateDate": "2023-08-24T14:05:58.0651592"},{"title": "周会","content": "每周周会要参加","status": 0,"id": 4,"createDate": "2023-07-25T03:42:51.686","updateDate": "2023-07-25T03:42:51.686"},{"title": "3333","content": "6666","status": 1,"id": 2,"createDate": "2023-07-25T02:51:58.562","updateDate": "2023-08-09T13:28:43.8087488"}],"hasPreviousPage": false,"hasNextPage": false}
}