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


    1、在WPF项目中添加Nuget包,搜索RestSharp安装

    2、新建Service文件夹,新建基础通用请求类BaseRequest.cs

    1. public class BaseRequest
    2. {
    3. public Method Method { get; set; }
    4. public string Route { get; set; }
    5. public string ContenType { get; set; } = "application/json";
    6. public string Parameter { get; set; }
    7. }

    3、在WPFProjectShared项目下新增类WebApiResponse.cs接收api返回信息

    1. public class WebApiResponse
    2. {
    3. public string Message { get; set; }
    4. public bool Status { get; set; }
    5. public object Result { get; set; }
    6. }
    7. public class WebApiResponse<T>
    8. {
    9. public string Message { get; set; }
    10. public bool Status { get; set; }
    11. public T Result { get; set; }
    12. }

    4、添加httpclient请求帮助类

    1. public class HttpRestClient
    2. {
    3. public readonly string apiUrl;
    4. protected readonly RestClient client;
    5. public HttpRestClient(string apiUrl)
    6. {
    7. this.apiUrl = apiUrl;
    8. client = new RestClient();
    9. }
    10. public async Task ExecuteAsync(BaseRequest baseRequest)
    11. {
    12. var request = new RestRequest(baseRequest.Method);
    13. request.AddHeader("Content-Type", baseRequest.ContenType.ToString());
    14. if (baseRequest.Parameter != null)
    15. request.AddParameter("param", JsonConvert.SerializeObject(baseRequest.Parameter), ParameterType.RequestBody);
    16. client.BaseUrl = new Uri(apiUrl + baseRequest.Route);
    17. var response = await client.ExecuteAsync(request);
    18. if (response.StatusCode == System.Net.HttpStatusCode.OK)
    19. return JsonConvert.DeserializeObject(response.Content);
    20. else
    21. return new WebApiResponse()
    22. {
    23. Status = false,
    24. Result = null,
    25. Message = response.ErrorMessage
    26. };
    27. }
    28. public async Task<WebApiResponse<T>> ExecuteAsync<T>(BaseRequest baseRequest)
    29. {
    30. var request = new RestRequest(baseRequest.Method);
    31. request.AddHeader("Content-Type", baseRequest.ContenType);
    32. if (baseRequest.Parameter != null)
    33. request.AddParameter("param", JsonConvert.SerializeObject(baseRequest.Parameter), ParameterType.RequestBody);
    34. client.BaseUrl = new Uri(apiUrl + baseRequest.Route);
    35. var response = await client.ExecuteAsync(request);
    36. if (response.StatusCode == System.Net.HttpStatusCode.OK)
    37. return JsonConvert.DeserializeObject>(response.Content);
    38. else
    39. return new WebApiResponse()
    40. {
    41. Status = false,
    42. Message = response.ErrorMessage
    43. };
    44. }
    45. }

    5、新增接口IBaseService,添加增删改查方法

    1. public interface IBaseService<TEntity> where TEntity : class
    2. {
    3. Task> AddAsync(TEntity entity);
    4. Task> UpdateAsync(TEntity entity);
    5. Task DeleteAsync(int id);
    6. Task> GetFirstOfDefaultAsync(int id);
    7. Task>> GetAllPageListAsync(QueryParameter parameter);
    8. }

    6、实现接口BaseService

    1. public class BaseService<TEntity> : IBaseService<TEntity> where TEntity : class
    2. {
    3. private readonly HttpRestClient client;
    4. private readonly string serviceName;
    5. public BaseService(HttpRestClient client, string serviceName)
    6. {
    7. this.client = client;
    8. this.serviceName = serviceName;
    9. }
    10. public async Task> AddAsync(TEntity entity)
    11. {
    12. BaseRequest request = new BaseRequest();
    13. request.Method = RestSharp.Method.POST;
    14. request.Route = $"api/{serviceName}/Add";
    15. request.Parameter = entity;
    16. return await client.ExecuteAsync(request);
    17. }
    18. public async Task DeleteAsync(int id)
    19. {
    20. BaseRequest request = new BaseRequest();
    21. request.Method = RestSharp.Method.DELETE;
    22. request.Route = $"api/{serviceName}/Delete?id={id}";
    23. return await client.ExecuteAsync(request);
    24. }
    25. public async Task>> GetAllPageListAsync(QueryParameter parameter)
    26. {
    27. BaseRequest request = new BaseRequest();
    28. request.Method = RestSharp.Method.GET;
    29. request.Route = $"api/{serviceName}/GetAllPageListToDo?pageIndex={parameter.PageIndex}" + $"&pageSize={parameter.PageSize}" + $"&search={parameter.Search}";
    30. return await client.ExecuteAsync>(request);
    31. }
    32. public async Task> GetFirstOfDefaultAsync(int id)
    33. {
    34. BaseRequest request = new BaseRequest();
    35. request.Method = RestSharp.Method.GET;
    36. request.Route = $"api/{serviceName}/Get?id={id}";
    37. return await client.ExecuteAsync(request);
    38. }
    39. public async Task> UpdateAsync(TEntity entity)
    40. {
    41. BaseRequest request = new BaseRequest();
    42. request.Method = RestSharp.Method.POST;
    43. request.Route = $"api/{serviceName}/Update";
    44. request.Parameter = entity;
    45. return await client.ExecuteAsync(request);
    46. }
    47. }

    7、新增IToDoService接口,继承IBaseService接口

    1. public interface IToDoService:IBaseService<ToDoDto>
    2. {
    3. }

    8、新增ToDoService类,继承BaseService类和接口IToDoService

    1. public class ToDoService : BaseService<ToDoDto>, IToDoService
    2. {
    3. public ToDoService(HttpRestClient client) : base(client, "ToDo")
    4. {
    5. }
    6. }

    9、在客户端App.xaml中注册httprestclient、注册默认服务的地址、注册服务

    1. ///
    2. /// Interaction logic for App.xaml
    3. ///
    4. public partial class App : PrismApplication
    5. {
    6. protected override Window CreateShell()
    7. {
    8. return Container.Resolve();
    9. }
    10. protected override void RegisterTypes(IContainerRegistry containerRegistry)
    11. {
    12. //注册httprestclient
    13. containerRegistry.GetContainer().Register(made: Parameters.Of.Type<string>(serviceKey: "webUrl"));
    14. //注册默认服务的地址
    15. containerRegistry.GetContainer().RegisterInstance(@"http://localhost:5000/", serviceKey: "webUrl");
    16. //注册服务
    17. containerRegistry.Register();
    18. containerRegistry.RegisterForNavigation();
    19. containerRegistry.RegisterForNavigation();
    20. containerRegistry.RegisterForNavigation();
    21. containerRegistry.RegisterForNavigation();
    22. containerRegistry.RegisterForNavigation();
    23. containerRegistry.RegisterForNavigation();
    24. containerRegistry.RegisterForNavigation();
    25. }
    26. }

    10、修改ToDoViewModel的代码,添加ToDoService服务,修改CreateToDoList 代码

    1. private readonly IToDoService toDoService;
    2. public ToDoViewModel(IToDoService toDoService)
    3. {
    4. ToDoDtos = new ObservableCollection();
    5. AddCommand = new DelegateCommand(Add);
    6. this.toDoService = toDoService;
    7. CreateToDoList();
    8. }
    9. private async void CreateToDoList()
    10. {
    11. var todoResult = await toDoService.GetAllPageListAsync(new WPFProjectShared.Parameters.QueryParameter
    12. {
    13. PageIndex = 0,
    14. PageSize = 100
    15. });
    16. if (todoResult.Status)
    17. {
    18. toDoDtos.Clear();
    19. foreach (var item in todoResult.Result.Items)
    20. {
    21. toDoDtos.Add(item);
    22. }
    23. }
    24. }

    11、右击解决方案-属性,设置多项目同时启动

    12、F5启动项目,点击【待办事项】,显示了待办事项的列表这和webapi中返回的待办事项Json数据一样。

    1. {
    2. "message": null,
    3. "status": true,
    4. "result": {
    5. "pageIndex": 0,
    6. "pageSize": 100,
    7. "totalCount": 5,
    8. "totalPages": 1,
    9. "indexFrom": 0,
    10. "items": [
    11. {
    12. "title": "测试新增待办事项",
    13. "content": "测试新增待办事项",
    14. "status": 0,
    15. "id": 2009,
    16. "createDate": "2023-11-22T15:48:50.8859172",
    17. "updateDate": "2023-11-22T15:48:50.8861276"
    18. },
    19. {
    20. "title": "测试api",
    21. "content": "测试api",
    22. "status": 1,
    23. "id": 1009,
    24. "createDate": "2023-08-29T16:41:44.93631",
    25. "updateDate": "2023-11-22T15:20:45.5035496"
    26. },
    27. {
    28. "title": "测试AutoMapper",
    29. "content": "AutoMapper",
    30. "status": 1,
    31. "id": 1008,
    32. "createDate": "2023-08-09T05:58:46.957",
    33. "updateDate": "2023-08-24T14:05:58.0651592"
    34. },
    35. {
    36. "title": "周会",
    37. "content": "每周周会要参加",
    38. "status": 0,
    39. "id": 4,
    40. "createDate": "2023-07-25T03:42:51.686",
    41. "updateDate": "2023-07-25T03:42:51.686"
    42. },
    43. {
    44. "title": "3333",
    45. "content": "6666",
    46. "status": 1,
    47. "id": 2,
    48. "createDate": "2023-07-25T02:51:58.562",
    49. "updateDate": "2023-08-09T13:28:43.8087488"
    50. }
    51. ],
    52. "hasPreviousPage": false,
    53. "hasNextPage": false
    54. }
    55. }

  • 相关阅读:
    深信服科技:2023网络安全深度洞察及2024年趋势研判报告
    关于2022年度深圳市技术攻关重大项目的申报通知
    哈工大2024春季计算机系统大作业(水平有限,仅供参考)
    Python快速计算24点游戏并获取表达式
    Django配置多个数据库(两种方法)
    Duchefa丨MS培养基含维生素说明书
    JVM(一)
    OceanBase 4.1解读:读写兼备的DBLink让数据共享“零距离”
    leetcode 1208.尽可能使字符串相等 滑动窗口
    Spring ioc aop
  • 原文地址:https://blog.csdn.net/yigu4011/article/details/132716595