WPF实战项目十五(客户端):RestSharp的使用

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}
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hqwc.cn/news/206044.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Django学习日志09

choices参数的使用 """对于以上可能被我们列举完的字段我们一般都是选择使用choices参来做""" class UserInfo(models.Model):username models.CharField(max_length64)password models.CharField(max_length32)# 先写一个映射关系gender_cho…

Python实现四个组成不相同且无重复的三位数

前言 大家早好、午好、晚好吖 ❤ ~欢迎光临本文章 如果有什么疑惑/资料需要的可以点击文章末尾名片领取源码 1.题目&#xff1a;有四个数字&#xff1a;1、2、3、4&#xff0c;能组成多少个互不相同且无重复数字的三位数&#xff1f;各是多少&#xff1f; for i in range(1,…

Leo赠书活动-10期 【AIGC重塑教育 AI大模型驱动的教育变革与实践】文末送书

✅作者简介&#xff1a;大家好&#xff0c;我是Leo&#xff0c;热爱Java后端开发者&#xff0c;一个想要与大家共同进步的男人&#x1f609;&#x1f609; &#x1f34e;个人主页&#xff1a;Leo的博客 &#x1f49e;当前专栏&#xff1a; 赠书活动专栏 ✨特色专栏&#xff1a;…

数字IC基础:有符号数和无符号数加、减法的Verilog设计

相关阅读 数字IC基础https://blog.csdn.net/weixin_45791458/category_12365795.html?spm1001.2014.3001.5482 本文是对数字IC基础&#xff1a;有符号数和无符号数的加减运算一文中的谈到的有符号数加减法的算法进行Verilog实现&#xff0c;有关算法细节请阅读原文&#xff0…

【追求卓越02】数据结构--链表

引导 今天我们进入链表的学习&#xff0c;我相信大家对链表都很熟悉。链表和数组一样&#xff0c;作为最基础的数据结构。在我们的工作中常常会使用到。但是我们真的了解到数组和链表的区别吗&#xff1f;什么时候使用数组&#xff0c;什么时候使用链表&#xff0c;能够正确的选…

微信小程序:This Mini Program cannot be opened as your Weixin version is out-of-date.

项目场景&#xff1a; 问题描述 升级基础库3.2.0&#xff0c;然后PC端整个小程序都打不开了&#xff0c;点击小程序提示”This Mini Program cannot be opened as your Weixin version is out-of-date. Update Weixin to the latest version.“&#xff0c;并且点击Update Wei…

Request 爬虫的 SSL 连接问题深度解析

SSL 连接简介 SSL&#xff08;Secure Sockets Layer&#xff09;是一种用于确保网络通信安全性的加密协议&#xff0c;广泛应用于互联网上的数据传输。在数据爬取过程中&#xff0c;爬虫需要与使用 HTTPS 协议的网站进行通信&#xff0c;这就牵涉到了 SSL 连接。本文将深入研究…

搜维尔科技:电影中面部动画的演变,Faceware面部捕捉成后起之秀

面部动画是电影中角色表演的一个重要方面&#xff0c;尤其是在严重依赖电子动画、化妆效果和动作捕捉系统的奇幻电影中。在《龙与地下城&#xff1a;盗贼荣耀》电影中&#xff0c;龙裔角色的面部动画是一个复杂的系统&#xff0c;使该生物在大屏幕上栩栩如生。该系统依赖于一种…

浅析教学型数控车床使用案例

教学型数控车床是一种专为教学和培训设计的机床&#xff0c;它具有小型化、高精度和灵活性的特点&#xff0c;可以作为学校和技术学院的培训机器。下面是一个使用案例&#xff0c;以展示教学型数控车床在教学实训中的应用。 案例背景&#xff1a; 某职业技术学院的机械工程专业…

sd-webui-controlnet代码分析

controlnet前向代码解析_Kun Li的博客-CSDN博客文章浏览阅读1.5k次。要分析下controlnet的yaml文件&#xff0c;在params中分成了4个部分&#xff0c;分别是control_stage_config、unnet_config、first_stage_config、cond_stage_config。其中control_stage_config对应的是13层…

实时数据备份实践inotify和rsync联动

目录 一、实时数据备份 1.实时数据备份 2.定时任务周期性的数据备份 3.实时数据备份 4.Inotify机制 二、实践 1.实时复制环境准备 2.实时复制概念 3.InofityRsync实施复制实战 4.配置好rsync守护进程 5.检查linux是否支持inotify 6.安装inotyify--tools 7.inotify…

【图像分类】基于深度学习的垃圾分类系统的设计与实现(ResNet网络,附代码和数据集)

写在前面: 首先感谢兄弟们的关注和订阅,让我有创作的动力,在创作过程我会尽最大能力,保证作品的质量,如果有问题,可以私信我,让我们携手共进,共创辉煌。(专栏订阅用户订阅专栏后免费提供数据集和源码一份,超级VIP用户不在服务范围之内,不想订阅专栏的兄弟们可以私信…