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

news2024/9/21 14:26:29

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);

            else
                return 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);

            else
                return 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)
        {
            //注册httprestclient
            containerRegistry.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.coloradmin.cn/o/1238192.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

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层…

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

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

好题分享(2023.11.12——2023.11.18)

目录 ​ 前情回顾&#xff1a; 前言&#xff1a; 题目一&#xff1a;《有效括号》 思路&#xff1a; 总结&#xff1a; 题目二&#xff1a;《用队列实现栈》 思路&#xff1a; 总结&#xff1a; 题目三&#xff1a;《用栈实现队列》 思路&#xff1a; 总结 &#x…

验证码 | 可视化一键管控各场景下的风险数据

目录 查看今日验证数据 查看未来趋势数据 验证码作为人机交互界面经常出现的关键要素&#xff0c;是身份核验、防范风险、数据反爬的重要组成部分&#xff0c;广泛应用网站、App上&#xff0c;在注册、登录、交易、交互等各类场景中发挥着巨大作用&#xff0c;具有真人识别、身…

C#winfrom端屏幕截图功能的简单实现(修改了屏幕的缩放比例后,截图功能异常,慎用!!!)

文章目录 1 主要文件1.1 FrmScreenShot.cs1.2 FrmScreenShot.Designer.cs1.1 Utility.cs 在发现有一款播放软件禁止截图功能后&#xff0c;使用了其他的截图工具发现都会被播放软件禁用掉截图功能&#xff0c;想了下试着自己做一个截图工具&#xff0c;也可以方便将截图工具添加…

【追求卓越01】数据结构--数组

引导 这一章节开始&#xff0c;正式进入数据结构与算法的学习过程中。由简到难&#xff0c;先开始学习最基础的数据结构--数组。 我相信对于数组&#xff0c;大家肯定是不陌生&#xff0c;因为数组在大多数的语言中都有&#xff0c;也是大家在编程中常常会接触到的。我不会说数…

文心大模型商业化领跑,百度在自我颠覆中重构生长力

随着科技巨头竞逐AI大模型&#xff0c;人工智能技术成为今年最受瞩目的新技术。但是&#xff0c;AI大模型的创新之路&#xff0c;还缺少一个足够有力的商业化答案。 作为全球最先发布大模型的互联网大厂&#xff0c;百度能否加速大模型的应用落地&#xff0c;以及文心大模型能…

【23真题】劝退211!今年突变3门课!

今天分享的是23年云南大学847&#xff08;原827&#xff09;的考研试题及解析。同时考SSDSP的院校做一个少一个&#xff0c;珍惜&#xff01;同时考三门课的院校&#xff0c;复习压力极大&#xff0c;但是也会帮大家劝退很多人&#xff0c;有利有弊&#xff0c;请自行分析~ 本…

微信小程序开发者工具] ? Enable IDE Service (y/N) ESC[27DESC[27C

在HBuilder运行微信小程序开发者工具报错 如何解决 打开微信小程序开发者工具打开设置--->安全设置--->服务器端口选择打开就可以啦

短时傅里叶变换函数编写

文章目录 傅里叶变换与短时傅里叶变换什么是窗&#xff1f;自己对手实现短时傅里叶变换 傅里叶变换与短时傅里叶变换 在了解短时傅里叶变换之前&#xff0c;首先要知道是什么是傅里叶变换&#xff08; fourier transformation&#xff0c;FT&#xff09;&#xff0c;傅里叶变换…

从 PUGC 到 SGC,普通店员也能用 AI 运营「粉丝群」

同一种文案风格反复使用&#xff0c;商品展示图也单调雷同&#xff0c;要直播时就直接「扔」个链接&#xff0c;社群、朋友圈这些品牌的私域重地有时极易被忽视&#xff0c;而变得千篇一律、简单粗暴。 但是&#xff0c;以内容驱动业务增长&#xff0c;已经成为越来越多品牌在做…

【EI会议征稿】第五届人工智能、网络与信息技术国际学术会议(AINIT 2024)

第五届人工智能、网络与信息技术国际学术会议&#xff08;AINIT 2024&#xff09; 2024 5th International Seminar on Artificial Intelligence, Networking and Information Technology 第五届人工智能、网络与信息技术国际学术会议&#xff08;AINIT 2024&#xff09;将于…

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

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

Java计算时间差,距结束还有几天几小时几分钟

文章目录 1、写法2、备份3、LocalDate、LocalDateTime、Date、String互转 1、写法 //静态方法&#xff0c;传入年月日时分秒 LocalDateTime startTime LocalDateTime.of(2023, 11, 22, 15, 09, 59); LocalDateTime endTime LocalDateTime.of(2023, 11, 30, 0, 0, 0); //计算…

2023.11.22 -数据仓库

目录 https://blog.csdn.net/m0_49956154/article/details/134320307?spm1001.2014.3001.5501 1经典传统数仓架构 2离线大数据数仓架构 3数据仓库三层 数据运营层,源数据层&#xff08;ODS&#xff09;&#xff08;Operational Data Store&#xff09; 数据仓库层&#…

想打造私域流量帝国?先解决这4个难题!

一、谁是你的目标用户 1. 清晰界定目标用户&#xff1a;确定你的产品或服务主要面向的用户群体&#xff0c;如年龄段、性别、职业等特征。 2. 确定最有购买力的用户群体&#xff1a;分析哪个用户群体在购买你的产品或服务时更容易乐于支付&#xff0c;并将其作为重点关注对象。…

程序的执行原理(下)

文章目录 系统的硬件组成总线I/0设备主存处理器程序计数器&#xff08;PC&#xff09;加载:存储:操作:跳转: 运行 hello 程序读入寄存器&#xff0c;再把它存放到内存从磁盘加载程序到主存处理器执行程序并显示 参考 系统的硬件组成 总线 贯穿整个系统的是一组电子管道&#…

Java爬虫框架下代理使用中的TCP连接池问题及解决方案

引言 当使用Java爬虫框架进行代理爬取时&#xff0c;可能会遇到TCP连接池问题&#xff0c;导致"java.net.BindException: Cannot assign requested address"等错误。本文将介绍如何以爬取小红书为案例&#xff0c;解决Java爬虫框架中代理使用中的TCP连接池问题&…

连线鑫云:企业级存储设备制造商!

我们在今年的双11专场直播中&#xff0c;有幸邀请到了鑫云存储的嘉宾与我们连线&#xff0c;为大家作了一场精彩的分享。 这里&#xff0c;首先感谢鑫云存储对水经注的大力支持&#xff01; 现在&#xff0c;我们将嘉宾分享的内容进行简单整理&#xff0c;并以图文的方式与大家…

如何隐藏自己的代码(很酷)

1.引入 幻想当我们成为一名优秀的程序员&#xff0c;有着各大公司想要买我们的代码&#xff0c;但我们并不想要让他们知道我们代码的实现&#xff0c;毕竟一复制便可以解决&#xff0c;这里我们希望有一种方法可以把我们的核心代码给隐藏掉&#xff0c;那我们又应该怎么去实现呢…