10.使用RestSharps请求WebAPI

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

    }

 

posted @ 2024-02-11 09:15  野码  阅读(203)  评论(0编辑  收藏  举报