WPF实战学习笔记14-使用Todo类的GetAll接口

使用Todo类的GetAll接口

添加包:RestSharp(V:110)

删除不再需要的文件

  • Mytodo/Common/TodoDto.cs
  • Mytodo/Common/MemoDto.cs

新建基础类或接口

MyToDo.Share/ApiResponse.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MyToDo.Share
{
    public class ApiResponse
    {
        public string? Message { get; set; }

        public bool Status { get; set; }

        public object? Result { get; set; }
    }

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

        public bool Status { get; set; }

        public T? Result { get; set; }
    }
}

MyToDo.Share/IPageList.cs

namespace MyToDo.Share.Contact
{
    using System.Collections.Generic;
    /// <summary>
    /// Provides the interface(s) for paged list of any type.
    /// 为任何类型的分页列表提供接口
    /// </summary>
    /// <typeparam name="T">The type for paging.分页的类型</typeparam>
    public interface IPagedList<T>
    {
        /// <summary>
        /// Gets the index start value.
        /// 获取索引起始值
        /// </summary>
        /// <value>The index start value.</value>
        int IndexFrom { get; }
        /// <summary>
        /// Gets the page index (current).
        /// 获取页索引(当前)
        /// </summary>
        int PageIndex { get; }
        /// <summary>
        /// Gets the page size.
        /// 获取页面大小
        /// </summary>
        int PageSize { get; }
        /// <summary>
        /// Gets the total count of the list of type <typeparamref name="T"/>
        /// 获取类型列表的总计数
        /// </summary>
        int TotalCount { get; }
        /// <summary>
        /// Gets the total pages.
        /// 获取页面总数
        /// </summary>
        int TotalPages { get; }
        /// <summary>
        /// Gets the current page items.
        /// 获取当前页项
        /// </summary>
        IList<T> Items { get; }
        /// <summary>
        /// Gets the has previous page.
        /// 获取前一页
        /// </summary>
        /// <value>The has previous page.</value>
        bool HasPreviousPage { get; }

        /// <summary>
        /// Gets the has next page.
        /// 获取下一页
        /// </summary>
        /// <value>The has next page.</value>
        bool HasNextPage { get; }
    }
}

MyToDo.Share/PageList.cs

新建BaseRequest

新建文件:Mytodo/Service/BaseRequest.cs

using RestSharp;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Mytodo.Service
{
    public class BaseRequest
    {
        public Method Method { get; set; }

        public string? Route { get; set; }

        public string ContentType { get; set; } = "application/json";

        public object? Parameter { get; set; }
    }
}

添加Http客户端服务

新建文件Mytodo/Service/HttpRestClient.cs

using Newtonsoft.Json;
using RestSharp;
using RestSharp.Extensions;
using RestSharp.Serializers;
using RestSharp.Authenticators;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MyToDo.Share;


namespace Mytodo.Service
{
    /// <summary>
    /// Http本地客户端
    /// </summary>
    public class HttpRestClient
    {

        private readonly string? apiUrl;

        protected readonly RestClient? client;

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

        /// <summary>
        /// 异步执行
        /// </summary>
        /// <param name="baseRequest"></param>
        /// <returns></returns>
        public async Task<ApiResponse> ExecuteAsync(BaseRequest baseRequest)
        {
            //uri
            var uri = new Uri(apiUrl + baseRequest.Route);

            //new restrequest
            //add uri
            var request = new RestRequest(uri);
            //add method
            request.Method=baseRequest.Method;
            //add header
            request.AddHeader("Content-Type", baseRequest.ContentType);
            //add Parameter
            if (baseRequest.Parameter != null)
                request.AddParameter("param", JsonConvert.SerializeObject(baseRequest.Parameter), ParameterType.RequestBody);

            //判断client是否为空
            if (client == null)
                return new ApiResponse()
                {
                    Status = false,
                    Result = null,
                    Message = "client为空"
                };

            //执行
            var response = await client.ExecuteAsync(request);

            //如果成功则执行序列化任务,否则返回失败代码
            if (response.StatusCode == System.Net.HttpStatusCode.OK)
                return JsonConvert.DeserializeObject<ApiResponse>(response.Content);

            else

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

        public async Task<ApiResponse<T>> ExecuteAsync<T>(BaseRequest baseRequest)
        {
            //uri
            var uri = new Uri(apiUrl + baseRequest.Route);

            //new restrequest
            //add uri
            var request = new RestRequest(uri);
            //add method
            request.Method = baseRequest.Method;
            //add header
            request.AddHeader("Content-Type", baseRequest.ContentType);
            //add Parameter
            if (baseRequest.Parameter != null)
                request.AddParameter("param", JsonConvert.SerializeObject(baseRequest.Parameter), ParameterType.RequestBody);

            //判断client是否为空
            if (client == null)
                return new ApiResponse<T>()
                {
                    Status = false,
                    Message = "client为空"
                };

            //执行
            var response = await client.ExecuteAsync(request);

            //如果成功则执行序列化任务,否则返回失败代码
            if (response.StatusCode == System.Net.HttpStatusCode.OK)
                return  JsonConvert.DeserializeObject<ApiResponse<T>>(response.Content);

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

  1. 在HttpRestClient类中,因最新RestSharp版本为110,与老师不同,其中的RestRequest初始化流程也与老师给的不同,详细可在VS中参考github中给出的example。我在这里给出我的修改:https://www.cnblogs.com/dongxinya/p/17556221.html

    PS:后续有问题,我还是回退到了老师的版本。

  2. 在我这里,当Request链接中的parameter的Search参数为空时,会返回失败,所以上述代码中增加了判断Search是否为空,为空则在请求中要删除Search参数。

创建Basevice接口

新建文件Mytodo/Service/IBaseService.cs

using MyToDo.Share;
using MyToDo.Share.Parameters;
using MyToDo.Share.Contact;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Mytodo.Service
{
    public interface IBaseService<TEnity> where TEnity : class
    {
        Task<ApiResponse<TEnity>> AddAsync(TEnity enity);

        Task<ApiResponse<TEnity>> UpdateAsync(TEnity enity);

        Task<ApiResponse> DeleteAsync(int id );

        Task<ApiResponse<TEnity>> GetFirstOfDefaultAsync(int id);

        Task<ApiResponse<PagedList<TEnity>>> GetAllAsync(QueryParameter parameter);

        

        
    }
}

实现Basevice接口

新建文件Mytodo/Service/BaseService.cs

using MyToDo.Share;
using MyToDo.Share.Contact;
using MyToDo.Share.Parameters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Mytodo.Service
{
    public class BaseService<TEnity> : IBaseService<TEnity> where TEnity : class
    {
        private readonly HttpRestClient client;
        private readonly string ServiceName;

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

        public async Task<ApiResponse<TEnity>> AddAsync(TEnity enity)
        {
            BaseRequest request = new BaseRequest();

            request.Method = RestSharp.Method.Post;
            request.Route = $"api[{ServiceName}]/Add";
            request.Parameter = enity;
            return await client.ExecuteAsync<TEnity>(request);
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<ApiResponse> 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<ApiResponse<PagedList<TEnity>>> GetAllAsync(QueryParameter parameter)
        {
            BaseRequest request = new BaseRequest();

            request.Method = RestSharp.Method.Get;

            //如果查询字段为空
            if (string.IsNullOrEmpty(parameter.Search))
                request.Route = $"api/{ServiceName}/GetAll?PageIndex={parameter.PageIndex}" + $"&PageSize={parameter.PageSize}";
            else
                request.Route = $"api/{ServiceName}/GetAll?PageIndex={parameter.PageIndex}" + $"&PageSize={parameter.PageSize}" + $"&search={parameter.Search}";

            return await client.ExecuteAsync<PagedList<TEnity>>(request);
        }

        public async Task<ApiResponse<TEnity>> GetFirstOfDefaultAsync(int id)
        {
            BaseRequest request = new BaseRequest();

            request.Method = RestSharp.Method.Get;
            request.Route = $"api/{ServiceName}/Get?id={id}";

            return await client.ExecuteAsync<TEnity>(request);
        }

        public async Task<ApiResponse<TEnity>> UpdateAsync(TEnity enity)
        {
            BaseRequest request = new BaseRequest();

            request.Method = RestSharp.Method.Post;
            request.Route = $"api/{ServiceName}/Update";
            request.Parameter = enity;
            return await client.ExecuteAsync<TEnity>(request);
        }
    }
}

创建TodoService接口

新建文件Mytodo/Service/ITodoService.cs

using Mytodo.Common.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MyToDo.Share.Models;

namespace Mytodo.Service
{
    public interface ITodoService:IBaseService<ToDoDto>
    {
    }
}

实现TodoService接口

新建文件Mytodo/Service/TodoService.cs

using Mytodo.Common.Models;
using MyToDo.Share;
using MyToDo.Share.Models;
using MyToDo.Share.Parameters;
using MyToDo.Share.Contact;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Media;
using System.Runtime.CompilerServices;

namespace Mytodo.Service
{
    public class TodoService:BaseService<ToDoDto>,ITodoService
    {
        private readonly HttpRestClient client;

        public TodoService(HttpRestClient client):base (client,"Todo")
        {
            this.client = client;
        }

        public async Task<ApiResponse<PagedList<ToDoDto>>> GetAllFilterAsync(TodoParameter parameter)
        {
            BaseRequest request = new BaseRequest();

            request.Method = RestSharp.Method.Get;

            request.Route =  $"api/ToDo/GetAll?pageIndex={parameter.PageIndex}" +
                $"&pageSize={parameter.PageSize}" +
                $"&search={parameter.Search}" +
                $"&status={parameter.Status}";

            return await client.ExecuteAsync<PagedList<ToDoDto>>(request);
        }
        
    }
}

依赖注入

修改 文件:Mytodo/App.xaml.cs

部分修改为:

protected override void RegisterTypes(IContainerRegistry containerRegistry)
{

    //注册服务
    containerRegistry.GetContainer().Register<HttpRestClient>(made: Parameters.Of.Type<string>(serviceKey: "webUrl"));
    containerRegistry.GetContainer().RegisterInstance(@"Http://localhost:19007/", serviceKey: "webUrl");

    containerRegistry.Register<ITodoService, TodoService>();

    containerRegistry.RegisterForNavigation<AboutView, AboutViewModel>();
    containerRegistry.RegisterForNavigation<SysSetView, SysSetViewModel>();
    containerRegistry.RegisterForNavigation<SkinView, SkinViewModel>();
    containerRegistry.RegisterForNavigation<IndexView, IndexViewModel>();
    containerRegistry.RegisterForNavigation<TodoView, TodoViewModel>();
    containerRegistry.RegisterForNavigation<MemoView, MemoViewModel>();
    containerRegistry.RegisterForNavigation<SettingsView, SettingsViewModel>();
}

修改ViewModel

修改文件:Mytodo/TodoViewModel.cs

  1. 增加字段
private readonly ITodoService service;
  1. 添加写入UI代码
async void CreateTodoList()
{
    var todoResult = await service.GetAllAsync(new MyToDo.Share.Parameters.QueryParameter { PageIndex = 0, PageSize = 100 });

    if (todoResult.Status)
    {
        todoDtos.Clear();
        foreach(var item in todoResult.Result.Items)
            todoDtos.Add(item);
    }
}
  1. 添加构造函数参数,并为参数赋值,同时调用写入UI函数

    public TodoViewModel(ITodoService service)
    {
        TodoDtos=new ObservableCollection<ToDoDto>();
        OpenRightContentCmd = new DelegateCommand(Add);
        this.service = service;
        //添加数据
        CreateTodoList();
    }
    

猜你喜欢

转载自blog.csdn.net/xinzhiya001/article/details/131909422
今日推荐