首页 > 其他分享 >10.使用RestSharps请求WebAPI

10.使用RestSharps请求WebAPI

时间:2024-02-11 09:22:06浏览次数:26  
标签:WebAPI 10 ResultData request RestSharps BaseRequest serviceName Method public

1.请求类

public class BaseRequest
    {
        /// <summary>
        /// 请求法式
        /// </summary>
        public RestSharp.Method Method { get; set; }
        /// <summary>
        /// 路由
        /// </summary>
        public string? Route { get; set; }
        /// <summary>
        /// 数据类型
        /// </summary>
        public string ContentType { get; set; } = "application/json;";
        /// <summary>
        /// 参数
        /// </summary>
        public object? Parameter { get; set; }
    }

 

2.http请求,ResultData是返回数据类

 [ExposedServiceAttribute(Lifetime.Singleton, AutoInitialize = true)]
    public class HttpRrestClient
    {
        private readonly string _url;
        private readonly RestClient _client;
        public HttpRrestClient()
        {
            _url = "https://localhost:7172/";
            _client = new RestClient();
        }

        public ResultData Execute(BaseRequest baseRequest)
        {
            var url = new Uri(_url + baseRequest.Route);
            var request = new RestRequest(url, baseRequest.Method);
            request.AddHeader("Content-Type", baseRequest.ContentType);
            //参数
            if (baseRequest.Parameter != null)
            {
                request.AddParameter("", JsonConvert.SerializeObject(baseRequest.Parameter)
                   , ParameterType.RequestBody);
            }
            //if (SessionUserInfos.SessionUserInfo != null)
            //    request.AddParameter("token", $"{SessionUserInfos.SessionUserInfo.Token}", ParameterType.HttpHeader);


            var response = _client.Execute(request);

            if (response.Content != null)
            {
                var jonsObj = JsonConvert.DeserializeObject<ResultData>(response.Content);
                return jonsObj;
            }
            return ResultData.Fail("API数据获取失败");

        }

        /// <summary>
        /// 分页数据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="baseRequest"></param>
        /// <returns></returns>
        public ResultData<PageListBack> ExecutePageList(BaseRequest baseRequest)
        {
            var url = new Uri(_url + baseRequest.Route);
            var request = new RestRequest(url, baseRequest.Method);
            request.AddHeader("Content-Type", baseRequest.ContentType);
            if (baseRequest.Parameter != null)
            {
                var parmert = JsonConvert.SerializeObject(baseRequest.Parameter);
                //post请求传实体类参数AddParameter第一个参数可以为空或者为application/json
                request.AddParameter("", parmert
                    , ParameterType.RequestBody);
                //添加token
                //string token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy9uYW1lIjoidV9hZG1pbiIsImh0dHA6Ly9zY2hlbWFzLm1pY3Jvc29mdC5jb20vd3MvMjAwOC8wNi9pZGVudGl0eS9jbGFpbXMvcm9sZSI6InJfYWRtaW4iLCJqdGkiOiJhZG1pbiIsIlVzZXJuYW1lIjoiQWRtaW4iLCJOYW1lIjoi6LaF57qn566h55CG5ZGYIiwibmJmIjoxNzAxOTEyMDIxLCJleHAiOjE3MDE5OTg0MjEsImlzcyI6Imp3dElzc3VlciIsImF1ZCI6Imp3dEF1ZGllbmNlIn0.c1mT5YJbKEV6eL7tap1TVxzE4urWGEI4jmsiX0vE73o";
                //request.AddParameter("token", $"Bearer {token}", ParameterType.HttpHeader);
            }
            var response = _client.Execute(request);
            if (response.Content != null)
            {
                var jonsObj = JsonConvert.DeserializeObject<ResultData<PageListBack>>(response.Content);
                return jonsObj;
            }
            return ResultData<PageListBack>.Fail("API数据获取失败");
        }
    }

 

3使用

添加两个文件夹IService和Service,那用户信息表来举例:

IService:

public interface IBaseService<T> where T : class
    {
        ResultData Insert(T entity);
        ResultData Update(T entity);
        ResultData Delete(int id);
        ResultData GetFirsOfDefault(int id);

    }
public interface IUserInfoService : IBaseService<UserInfo>
    {
        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        ResultData Login(UserInfo dto);

        /// <summary>
        /// 注册
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>

        ResultData Resgiter(UserInfo dto);
    }

 

Service:

 public class BaseService<T> : IBaseService<T> where T : class
    {
        private readonly HttpRrestClient client;
        private readonly string serviceName;

        public BaseService(HttpRrestClient client, string serviceName)
        {
            this.client = client;
            this.serviceName = serviceName;
        }

        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public ResultData Insert(T entity)
        {
            BaseRequest request = new BaseRequest();
            request.Method = RestSharp.Method.Post;
            request.Route = $"api/{serviceName}/Insert";//路由
            request.Parameter = entity;
            var resultData = client.Execute(request);
            return resultData;
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public ResultData Update(T entity)
        {
            BaseRequest request = new BaseRequest();
            request.Method = RestSharp.Method.Post;
            request.Route = $"api/{serviceName}/Update";//路由
            request.Parameter = entity;
            var resultData = client.Execute(request);
            return resultData;
        }

        /// <summary>
        /// 删除(此方法不用,重写软删除)
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ResultData Delete(int id)
        {
            BaseRequest request = new BaseRequest();
            request.Method = RestSharp.Method.Post;
            request.Route = $"api/{serviceName}/Delete?id={id}";//路由
            var resultData = client.Execute(request);
            return resultData;
        }

        /// <summary>
        /// 获取一条数据
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ResultData GetFirsOfDefault(int id)
        {
            BaseRequest request = new BaseRequest();
            request.Method = RestSharp.Method.Post;
            request.Route = $"api/{serviceName}/GetFirsOfDefault?id={id}";//路由
            // request.Parameter = page;
            var resultData = client.Execute(request);
            return resultData;
        }
    }

 

[ExposedService(Lifetime.Singleton, typeof(IUserInfoService))]
    public class UserInfoService : BaseService<UserInfo>, IUserInfoService
    {
        public HttpRrestClient Client { get; }
        private readonly string serviceName;
        public UserInfoService(HttpRrestClient client, string serviceName = "UserInfo") : base(client, serviceName)
        {
            Client = client;
            this.serviceName = serviceName;
        }



        public ResultData Login(UserInfo dto)
        {
            BaseRequest request = new BaseRequest();
            request.Method = RestSharp.Method.Post;
            request.Route = $"api/{serviceName}/Login";
            request.Parameter = dto;
            var resultData = Client.Execute(request);
            return resultData;
        }

        public ResultData Resgiter(UserInfo dto)
        {
            BaseRequest request = new BaseRequest();
            request.Method = RestSharp.Method.Post;
            request.Route = $"api/{serviceName}/Resgiter";
            request.Parameter = dto;
            var resultData = Client.Execute(request);
            return resultData;
        }

    }

 

标签:WebAPI,10,ResultData,request,RestSharps,BaseRequest,serviceName,Method,public
From: https://www.cnblogs.com/MingQiu/p/18013172

相关文章

  • 读千脑智能笔记10_人类智能存在的风险
    1. 人类智能存在的风险1.1. “末日时钟”1.1.1. 核战争引发的大火列为地球毁灭的主要原因1.1.2. 气候变化列为人类自我毁灭的第二大潜在原因1.2. 除非我们刻意加入自私的驱动力、动机或情感,否则智能机器并不会威胁到人类的生存1.2.1. 人类在不远的将来会创造出更多的......
  • 2024/2/10学习进度笔记
    RDD,学名可伸缩的分布式数据集(ResilientDistributedDataset)。是一种对数据集形态的抽象,基于此抽象,使用者可以在集群中执行一系列计算,而不用将中间结果落盘。而这正是之前MR抽象的一个重要痛点,每一个步骤都需要落盘,使得不必要的开销很高。对于分布式系统,容错支持是必不可少的。......
  • P1102 A-B 数对
    原题链接解法一:二分搜素首先我们知晓A-B=C,那么A=B+C,我们只需要遍历数组中的每一个元素然后在数组中搜素a[i]+c的值是否存在即可。Code #include<bits/stdc++.h>usingnamespacestd;typedeflonglongll;constintN=2e5+5;lla[N];intmain(){intn,c;l......
  • 创新指南|企业实施Gen AI面临的10大挑战
    文章列出了实现生成式人工智能(GenAI)成功的十大挑战。这些挑战涵盖了从数据管理和法律法规到处理能力、解释能力、准确性问题等多个方面。文章强调,尽管GenAI具有巨大的潜力,但要克服这些挑战以实现其在业务中的有效应用。这些挑战反映了目前GenAI领域面临的关键问题和正在进行的......
  • NOI 2010 做题笔记
    NOI2010Day1T1能量采集观察到\((0,0)\)与\((x,y)\)连线上的整点个数正好是\(\gcd(x,y)-1\)(不包括端点),于是总能量损失即为:\[\begin{aligned}{}&\sum\limits_{T=l}^{r}f(T,c)\sum\limits_{i=0}^{n}p_iT^i\\=&\sum\limits_{i=0}^{n}p_i\sum\limits_{T......
  • P2985 [USACO10FEB] Chocolate Eating S
    原题链接题解看到使最不开心的一天尽可能的开心,这是要使最小值尽可能的不小,二分思路由此而来,剩余的就是贪心模拟最坏时间复杂度约为$O(d·sum(H))≈5·10^4·log2(5·10^{10})≈1777060.45$坑点:剩下的巧克力要在最后一天全部吃完\(Code\)#include<bits/stdc++.h>#d......
  • 代码随想录算法训练营第十六天| 104.二叉树的最大深度 559.n叉树的最大深度 111.二
    104.二叉树的最大深度  题目链接:104.二叉树的最大深度-力扣(LeetCode)n叉树也一样思路:我的普通递归方法classSolution{public:intdepth(TreeNode*node,intd){intl=0,r=0;if(node->left==NULL&&node->right==NULL)returnd;if(node-......
  • Windows 10/11等 IPV4 IPV6 DNS 最多设置多少个?
    Windows10/11等IPV4IPV6DNS最多设置多少个?理论知识:在Windows10系统中,IPv4和IPv6的DNS设置是通过网络配置进行的。对于DNS服务器地址的数量,Windows10并没有明确限制用户设置的数量。然而,从实际操作性和网络配置的常规需求来看,通常情况下,大多数用户会设置一到两个DNS服务......
  • P10013 Tree Topological Order Counting 题解
    首先题目里面写了每一个数都有权值,一般这种题只能去想求出每一个的具体方案数,那么也就是我们得求出\(h_{i,j}\)表示在所有合法拓扑序中\(a_i=j\)的方案数。一颗树的拓扑序数量是\(\dfrac{n!}{\prodsiz_i}\),相信大家都知道。因为我们需要保证这一棵树满足拓扑排序的条件,不......
  • P10068 [CCO2023] Line Town 题解
    好题,但是感觉写起来有点屎。题目大意给定一个序列\(a\),你每次可以选择\(i\in[1,n-1]\),交换\(a_i,a_{i+1}\),并且给\(a_i,a_{i+1}\)取相反数。问你最少需要多少次交换才能使得序列非降,可能无解。做法首先考虑给偶数位置初始乘上\(-1\),然后操作变成交换相邻两个数,下面提......