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

2023-11-24 06:15

本文主要是介绍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);JsonSerializerSettings jsSetting = new JsonSerializerSettings();jsSetting.NullValueHandling = NullValueHandling.Ignore;if (response.StatusCode == System.Net.HttpStatusCode.OK)return JsonConvert.DeserializeObject<WebApiResponse>(response.Content, jsSetting);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);JsonSerializerSettings jsSetting = new JsonSerializerSettings();jsSetting.NullValueHandling = NullValueHandling.Ignore;if (response.StatusCode == System.Net.HttpStatusCode.OK)return JsonConvert.DeserializeObject<WebApiResponse<T>>(response.Content, jsSetting);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}
}

这篇关于WPF实战项目十五(客户端):RestSharp的使用的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/421385

相关文章

网页解析 lxml 库--实战

lxml库使用流程 lxml 是 Python 的第三方解析库,完全使用 Python 语言编写,它对 XPath表达式提供了良好的支 持,因此能够了高效地解析 HTML/XML 文档。本节讲解如何通过 lxml 库解析 HTML 文档。 pip install lxml lxm| 库提供了一个 etree 模块,该模块专门用来解析 HTML/XML 文档,下面来介绍一下 lxml 库

这15个Vue指令,让你的项目开发爽到爆

1. V-Hotkey 仓库地址: github.com/Dafrok/v-ho… Demo: 戳这里 https://dafrok.github.io/v-hotkey 安装: npm install --save v-hotkey 这个指令可以给组件绑定一个或多个快捷键。你想要通过按下 Escape 键后隐藏某个组件,按住 Control 和回车键再显示它吗?小菜一碟: <template

中文分词jieba库的使用与实景应用(一)

知识星球:https://articles.zsxq.com/id_fxvgc803qmr2.html 目录 一.定义: 精确模式(默认模式): 全模式: 搜索引擎模式: paddle 模式(基于深度学习的分词模式): 二 自定义词典 三.文本解析   调整词出现的频率 四. 关键词提取 A. 基于TF-IDF算法的关键词提取 B. 基于TextRank算法的关键词提取

使用SecondaryNameNode恢复NameNode的数据

1)需求: NameNode进程挂了并且存储的数据也丢失了,如何恢复NameNode 此种方式恢复的数据可能存在小部分数据的丢失。 2)故障模拟 (1)kill -9 NameNode进程 [lytfly@hadoop102 current]$ kill -9 19886 (2)删除NameNode存储的数据(/opt/module/hadoop-3.1.4/data/tmp/dfs/na

Hadoop数据压缩使用介绍

一、压缩原则 (1)运算密集型的Job,少用压缩 (2)IO密集型的Job,多用压缩 二、压缩算法比较 三、压缩位置选择 四、压缩参数配置 1)为了支持多种压缩/解压缩算法,Hadoop引入了编码/解码器 2)要在Hadoop中启用压缩,可以配置如下参数

Makefile简明使用教程

文章目录 规则makefile文件的基本语法:加在命令前的特殊符号:.PHONY伪目标: Makefilev1 直观写法v2 加上中间过程v3 伪目标v4 变量 make 选项-f-n-C Make 是一种流行的构建工具,常用于将源代码转换成可执行文件或者其他形式的输出文件(如库文件、文档等)。Make 可以自动化地执行编译、链接等一系列操作。 规则 makefile文件

如何用Docker运行Django项目

本章教程,介绍如何用Docker创建一个Django,并运行能够访问。 一、拉取镜像 这里我们使用python3.11版本的docker镜像 docker pull python:3.11 二、运行容器 这里我们将容器内部的8080端口,映射到宿主机的80端口上。 docker run -itd --name python311 -p

性能分析之MySQL索引实战案例

文章目录 一、前言二、准备三、MySQL索引优化四、MySQL 索引知识回顾五、总结 一、前言 在上一讲性能工具之 JProfiler 简单登录案例分析实战中已经发现SQL没有建立索引问题,本文将一起从代码层去分析为什么没有建立索引? 开源ERP项目地址:https://gitee.com/jishenghua/JSH_ERP 二、准备 打开IDEA找到登录请求资源路径位置

使用opencv优化图片(画面变清晰)

文章目录 需求影响照片清晰度的因素 实现降噪测试代码 锐化空间锐化Unsharp Masking频率域锐化对比测试 对比度增强常用算法对比测试 需求 对图像进行优化,使其看起来更清晰,同时保持尺寸不变,通常涉及到图像处理技术如锐化、降噪、对比度增强等 影响照片清晰度的因素 影响照片清晰度的因素有很多,主要可以从以下几个方面来分析 1. 拍摄设备 相机传感器:相机传

pdfmake生成pdf的使用

实际项目中有时会有根据填写的表单数据或者其他格式的数据,将数据自动填充到pdf文件中根据固定模板生成pdf文件的需求 文章目录 利用pdfmake生成pdf文件1.下载安装pdfmake第三方包2.封装生成pdf文件的共用配置3.生成pdf文件的文件模板内容4.调用方法生成pdf 利用pdfmake生成pdf文件 1.下载安装pdfmake第三方包 npm i pdfma