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

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

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

cs 复制代码
    public class BaseRequest
    {
        public Method Method { get; set; }
        public string Route { get; set; }
        public string ContenType { get; set; } = "application/json";
        public string Parameter { get; set; }
    }

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

cs 复制代码
public class WebApiResponse
    {
        public string Message { get; set; }

        public bool Status { get; set; }

        public object Result { get; set; }
    }

    public class WebApiResponse<T>
    {
        public string Message { get; set; }

        public bool Status { get; set; }

        public T Result { get; set; }
    }

4、添加httpclient请求帮助类

cs 复制代码
public class HttpRestClient
    {
        public readonly string apiUrl;
        protected readonly RestClient client;

        public HttpRestClient(string apiUrl)
        {
            this.apiUrl = apiUrl;
            client = new RestClient();
        }

        public async Task<WebApiResponse> ExecuteAsync(BaseRequest baseRequest)
        {
            var request = new RestRequest(baseRequest.Method);
            request.AddHeader("Content-Type", baseRequest.ContenType.ToString());

            if (baseRequest.Parameter != null)
                request.AddParameter("param", JsonConvert.SerializeObject(baseRequest.Parameter), ParameterType.RequestBody);
            client.BaseUrl = new Uri(apiUrl + baseRequest.Route);
            var response = await client.ExecuteAsync(request);

            JsonSerializerSettings jsSetting = new JsonSerializerSettings();
            jsSetting.NullValueHandling = NullValueHandling.Ignore;

            if (response.StatusCode == System.Net.HttpStatusCode.OK)
                return JsonConvert.DeserializeObject<WebApiResponse>(response.Content, jsSetting);

            else
                return new WebApiResponse()
                {
                    Status = false,
                    Result = null,
                    Message = response.ErrorMessage
                };

        }

        public async Task<WebApiResponse<T>> ExecuteAsync<T>(BaseRequest baseRequest)
        {
            var request = new RestRequest(baseRequest.Method);
            request.AddHeader("Content-Type", baseRequest.ContenType);
            if (baseRequest.Parameter != null)
                request.AddParameter("param", JsonConvert.SerializeObject(baseRequest.Parameter), ParameterType.RequestBody);
            client.BaseUrl = new Uri(apiUrl + baseRequest.Route);
            var response = await client.ExecuteAsync(request);

            JsonSerializerSettings jsSetting = new JsonSerializerSettings();
            jsSetting.NullValueHandling = NullValueHandling.Ignore;

            if (response.StatusCode == System.Net.HttpStatusCode.OK)
                return JsonConvert.DeserializeObject<WebApiResponse<T>>(response.Content, jsSetting);

            else
                return new WebApiResponse<T>()
                {
                    Status = false,
                    Message = response.ErrorMessage
                };
        }
    }

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

cs 复制代码
    public interface IBaseService<TEntity> where TEntity : class
    {
        Task<WebApiResponse<TEntity>> AddAsync(TEntity entity);
        Task<WebApiResponse<TEntity>> UpdateAsync(TEntity entity);
        Task<WebApiResponse> DeleteAsync(int id);
        Task<WebApiResponse<TEntity>> GetFirstOfDefaultAsync(int id);
        Task<WebApiResponse<PagedList<TEntity>>> GetAllPageListAsync(QueryParameter parameter);
    }

6、实现接口BaseService

cs 复制代码
public class BaseService<TEntity> : IBaseService<TEntity> where TEntity : class
    {
        private readonly HttpRestClient client;
        private readonly string serviceName;

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

        public async Task<WebApiResponse<TEntity>> AddAsync(TEntity entity)
        {
            BaseRequest request = new BaseRequest();
            request.Method = RestSharp.Method.POST;
            request.Route = $"api/{serviceName}/Add";
            request.Parameter = entity;
            return await client.ExecuteAsync<TEntity>(request);
        }

        public async Task<WebApiResponse> DeleteAsync(int id)
        {
            BaseRequest request = new BaseRequest();
            request.Method = RestSharp.Method.DELETE;
            request.Route = $"api/{serviceName}/Delete?Id={id}";
            return await client.ExecuteAsync(request);
        }

        public async Task<WebApiResponse<PagedList<TEntity>>> GetAllPageListAsync(QueryParameter parameter)
        {
            BaseRequest request = new BaseRequest();
            request.Method = RestSharp.Method.GET;
            request.Route = $"api/{serviceName}/GetAllPageListToDo?pageIndex={parameter.PageIndex}" + $"&pageSize={parameter.PageSize}" + $"&search={parameter.Search}";
            return await client.ExecuteAsync<PagedList<TEntity>>(request);
        }

        public async Task<WebApiResponse<TEntity>> GetFirstOfDefaultAsync(int id)
        {
            BaseRequest request = new BaseRequest();
            request.Method = RestSharp.Method.GET;
            request.Route = $"api/{serviceName}/Get?Id={id}";
            return await client.ExecuteAsync<TEntity>(request);
        }

        public async Task<WebApiResponse<TEntity>> UpdateAsync(TEntity entity)
        {
            BaseRequest request = new BaseRequest();
            request.Method = RestSharp.Method.POST;
            request.Route = $"api/{serviceName}/Update";
            request.Parameter = entity;
            return await client.ExecuteAsync<TEntity>(request);
        }
    }

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

cs 复制代码
    public interface IToDoService:IBaseService<ToDoDto>
    {
    }

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

cs 复制代码
    public class ToDoService : BaseService<ToDoDto>, IToDoService
    {
        public ToDoService(HttpRestClient client) : base(client, "ToDo")
        {
        }
    }

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

cs 复制代码
/// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : PrismApplication
    {
        protected override Window CreateShell()
        {
            return Container.Resolve<MainView>();
        }
        protected override void RegisterTypes(IContainerRegistry containerRegistry)
        {
            //注册httprestclient
            containerRegistry.GetContainer().Register<HttpRestClient>(made: Parameters.Of.Type<string>(serviceKey: "webUrl"));
            //注册默认服务的地址
            containerRegistry.GetContainer().RegisterInstance(@"http://localhost:5000/", serviceKey: "webUrl");
            //注册服务
            containerRegistry.Register<IToDoService, ToDoService>();

            containerRegistry.RegisterForNavigation<IndexView, IndexViewModel>();
            containerRegistry.RegisterForNavigation<MemoView, MemoViewModel>();
            containerRegistry.RegisterForNavigation<SettingsView, SettingsViewModel>();
            containerRegistry.RegisterForNavigation<ToDoView, ToDoViewModel>();
            containerRegistry.RegisterForNavigation<SkinView, SkinViewModel>();
            containerRegistry.RegisterForNavigation<AboutView, AboutViewModel>();
            containerRegistry.RegisterForNavigation<SystemSettingsView, SystemSettingsViewModel>();
        }
    }

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

cs 复制代码
private readonly IToDoService toDoService;
        public ToDoViewModel(IToDoService toDoService)
        {
            ToDoDtos = new ObservableCollection<ToDoDto>();
            AddCommand = new DelegateCommand(Add);
            this.toDoService = toDoService;
            CreateToDoList();
        }

private async void CreateToDoList()
        {
            var todoResult = await toDoService.GetAllPageListAsync(new WPFProjectShared.Parameters.QueryParameter
            {
                PageIndex = 0,
                PageSize = 100
            });
            if (todoResult.Status)
            {
                toDoDtos.Clear();
                foreach (var item in todoResult.Result.Items)
                {
                    toDoDtos.Add(item);
                }
            }

        }

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

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

cs 复制代码
{
  "message": null,
  "status": true,
  "result": {
    "pageIndex": 0,
    "pageSize": 100,
    "totalCount": 5,
    "totalPages": 1,
    "indexFrom": 0,
    "items": [
      {
        "title": "测试新增待办事项",
        "content": "测试新增待办事项",
        "status": 0,
        "id": 2009,
        "createDate": "2023-11-22T15:48:50.8859172",
        "updateDate": "2023-11-22T15:48:50.8861276"
      },
      {
        "title": "测试api",
        "content": "测试api",
        "status": 1,
        "id": 1009,
        "createDate": "2023-08-29T16:41:44.93631",
        "updateDate": "2023-11-22T15:20:45.5035496"
      },
      {
        "title": "测试AutoMapper",
        "content": "AutoMapper",
        "status": 1,
        "id": 1008,
        "createDate": "2023-08-09T05:58:46.957",
        "updateDate": "2023-08-24T14:05:58.0651592"
      },
      {
        "title": "周会",
        "content": "每周周会要参加",
        "status": 0,
        "id": 4,
        "createDate": "2023-07-25T03:42:51.686",
        "updateDate": "2023-07-25T03:42:51.686"
      },
      {
        "title": "3333",
        "content": "6666",
        "status": 1,
        "id": 2,
        "createDate": "2023-07-25T02:51:58.562",
        "updateDate": "2023-08-09T13:28:43.8087488"
      }
    ],
    "hasPreviousPage": false,
    "hasNextPage": false
  }
}
相关推荐
bluefox19794 小时前
使用 Oracle.DataAccess.Client 驱动 和 OleDB 调用Oracle 函数的区别
开发语言·c#
戒哥一心搞钱4 小时前
.Net Core重要组件
.netcore
djk88884 小时前
.net6.0(.net Core)读取 appsettings.json 配置文件
json·.net·.netcore
刘梦凡呀4 小时前
.NET Core发布网站报错 HTTP Error 500.31
.netcore
鲤籽鲲5 小时前
C# MethodTimer.Fody 使用详解
开发语言·c#·mfc
工业3D_大熊6 小时前
3D可视化引擎HOOPS Luminate场景图详解:形状的创建、销毁与管理
java·c++·3d·docker·c#·制造·数据可视化
yngsqq6 小时前
c#使用高版本8.0步骤
java·前端·c#
hccee9 小时前
C# IO文件操作
开发语言·c#
广煜永不挂科11 小时前
Devexpress.Dashboard的调用二义性
c#·express
当下就是最好11 小时前
WPF应用程序的生命周期-笔记
wpf