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

发布于:2025-04-20 ⋅ 阅读:(12) ⋅ 点赞:(0)

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)
     {
         //反序列化json
         LoginAccountDTO 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);
     }
 ​
 }

网站公告

今日签到

点亮在社区的每一天
去签到