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

RestSharp和Newtonsoft.Json结合发送和解析http

1.下载RestSharp和Newtonsoft.Json

image-20250417140927406

2编写ApiRequest和ApiResponse和调用工具类HttpRestClient

image-20250417141017271

请求模型

  /// <summary>/// 请求模型/// </summary>public class ApiRequest{/// <summary>/// 请求地址/api路由地址/// </summary>public string Route { get; set; }​/// <summary>/// 请求方式(Post,Get,Delete,Put)/// </summary>public Method Method { get; set; }​/// <summary>/// 请求参数/// </summary>public object Parameters {  get; set; }​/// <summary>/// 发送的数据类型(默认是json)/// </summary>public string ContentType { get; set; } = "application/json";}

接收模型

 /// <summary>/// 接收模型/// </summary>public class ApiResponse{/// <summary>/// 结果编码/// </summary>public int ResultCode { get; set; }​/// <summary>/// 结果信息/// </summary>public string Msg { get; set; }​/// <summary>/// 数据/// </summary>public object ResultData { get; set; }}

http调用工具类,要对应后端接口把baseUrl替换掉

 /// <summary>/// 调用api工具类/// </summary>public class HttpRestClient{private readonly RestClient Client;​private readonly string baseUrl = "http://localhost:10036/api/";public HttpRestClient(){Client = new RestClient();}/// <summary>/// 请求/// </summary>/// <param name="request">请求数据</param>/// <returns>接收数据</returns>public ApiResponse Execute(ApiRequest apiRequest){//请求方式RestRequest request = new RestRequest(apiRequest.Method);//请求内容request.AddHeader("Content-Type", apiRequest.ContentType);if (apiRequest.Parameters != null){request.AddParameter("param",JsonConvert.SerializeObject(apiRequest.Parameters),ParameterType.RequestBody);}​//请求地址Client.BaseUrl = new Uri(baseUrl + apiRequest.Route);​var res=Client.Execute(request);​//请求成功if (res.StatusCode == System.Net.HttpStatusCode.OK){//把json格式反序列化成对象return JsonConvert.DeserializeObject<ApiResponse>(res.Content);}//失败else{return new ApiResponse { ResultCode = -99, Msg = "服务器忙,请稍后" };}}}

3.Prism依赖注入HttpRestClient

  public partial class App : PrismApplication{protected override Window CreateShell(){//设置启动页return Container.Resolve<MainWin>();}​/// <summary>/// 依赖注入/// </summary>/// <param name="containerRegistry"></param>protected override void RegisterTypes(IContainerRegistry containerRegistry){containerRegistry.GetContainer().Register<HttpRestClient>(made: Parameters.Of.Type<string>(serviceKey: "webUrl"));​}​​}

4.用一个登录例子说明

 private void Login(){if (string.IsNullOrEmpty(LoginAccountDTO.Account) || string.IsNullOrEmpty(LoginAccountDTO.Password)){//MessageBox.Show("账号或密码未输入");aggregator.GetEvent<MsgEvent>().Publish("账号或密码未输入");return;}​//创建请求ApiRequest apiRequest = new ApiRequest();apiRequest.Method = RestSharp.Method.GET;LoginAccountDTO.Password=Md5Helper.GetMd5(LoginAccountDTO.Password);apiRequest.Route = $"Account/Login?account={LoginAccountDTO.Account}&password={LoginAccountDTO.Password}";ApiResponse response = httpRestClient.Execute(apiRequest);​//登陆成功if (response.ResultCode == 1){//反序列化jsonLoginAccountDTO loginAccountDTO = JsonConvert.DeserializeObject<LoginAccountDTO>(response.ResultData.ToString());DialogParameters parameters = new DialogParameters();parameters.Add("LoginName", loginAccountDTO.Name);RequestClose(new DialogResult(ButtonResult.OK, parameters));}//登陆失败else{//MessageBox.Show(response.Msg);aggregator.GetEvent<MsgEvent>().Publish(response.Msg);}​}

相关文章:

  • 协同推荐算法实现的智能商品推荐系统 - [基于springboot +vue]
  • 矢量网络分析仪(VNA)能测什么?5大核心功能与典型应用场景详解
  • 高性能实现手机号模糊查询
  • IDEA2024 pom.xml依赖文件包报红解决
  • EM储能网关ZWS智慧储能云应用(9) — 远程OTA升级
  • RISC-V简介
  • 规范化与反规范化策略白皮书
  • C++解析操作mat文件方法-基于vs2019
  • OCC中的参数方程简介
  • 【Python学习笔记】Pandas实现Excel质检记录表初审、复核及质检统计
  • SadTalker 多表情运行需求
  • Rust 与 JavaScript 的 WebAssembly 互操作指南
  • CSS核心笔记001
  • python学习—合并多个word文档
  • ffmpeg无损转格式的命令行
  • 易境通WMS系统俄罗斯物流解决方案:告别“最后一公里”烦恼
  • 智能存储柜对比传统WMS管理模式的优势介绍
  • 数据通信学习笔记之OSPF路由汇总
  • 使用python帮助艺术家完成角色动画和服装模型等任务
  • JESD204B接收器核心实现和系统级关键细节
  • 山东:小伙为救同学耽误考试属实,启用副题安排考试
  • 七旬男子驾“老头乐”酒驾被查,曾有两次酒驾两次肇事记录
  • 回望乡土:对媒介化社会的反思
  • 俄乌拟在土耳其举行会谈,特朗普:我可能飞过去
  • 广西壮族自治区党委政法委副书记李文博接受审查调查
  • 区域国别学视域下的东亚文化交涉