当前位置: 首页 > article >正文

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

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

            JsonSerializerSettings jsSetting = new JsonSerializerSettings();
            jsSetting.NullValueHandling = NullValueHandling.Ignore;

            if (response.StatusCode == System.Net.HttpStatusCode.OK)
                return JsonConvert.DeserializeObject<WebApiResponse<T>>(response.Content, jsSetting);

            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.kler.cn/a/147565.html

相关文章:

  • SobarQube实现PDF报告导出
  • 利用OpenAI进行测试需求分析——从电商网站需求到测试用例的生成
  • Prometheus监控SQL SERVER常用指标和PromQL预警
  • 全面解读 USB Key:定义、使用场景、加密技术及 Java 实现
  • RabbitMQ实战启程:从原理到部署的全方位探索(上)
  • Python_爬虫1_Requests库入门
  • WordPress老是提示无法连接到FTP服务器
  • 【产品设计】如何设计SaaS商业模式
  • leetcode目标和
  • 4.3-Linux网络命名空间
  • FFmepg 核心开发库及重要数据结构与API
  • 基于可微分渲染器的相机位置优化【PyTorch3D】
  • CPU、GPU、TPU内存子系统架构
  • Python入门学习篇(三)——比较运算符赋值运算符逻辑运算符成员运算符
  • 【JavaEE初阶】Thread 类及常见方法、线程的状态
  • 集成学习的两种常见策略:bagging VS. boosting
  • KVM虚拟机的NAT网络模式原理及过程展示
  • 谈谈中间件设计的思路
  • vue 浏览器版本兼容问题解决方案
  • 解决SQLyog连接MySQL8时报错:错误号码2058
  • Vatee万腾的科技远行:vatee数字化力量的前瞻发现
  • LeetCode Hot100 114.二叉树展开为链表
  • 企业网络中的身份安全
  • Redis与Mysql的数据强一致性方案
  • C语言——猜凶手
  • 2023_Spark_实验二十二:Zookeeper的集群安装