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
{
public string? Message { get; set; }
public bool Status { get; set; }
public T? Result { get; set; }
}
}
namespace MyToDo.Share.Contact
{
using System.Collections.Generic;
///
/// Provides the interface(s) for paged list of any type.
/// 为任何类型的分页列表提供接口
///
/// The type for paging.分页的类型
public interface IPagedList
{
///
/// Gets the index start value.
/// 获取索引起始值
///
/// The index start value.
int IndexFrom { get; }
///
/// Gets the page index (current).
/// 获取页索引(当前)
///
int PageIndex { get; }
///
/// Gets the page size.
/// 获取页面大小
///
int PageSize { get; }
///
/// Gets the total count of the list of type
/// 获取类型列表的总计数
///
int TotalCount { get; }
///
/// Gets the total pages.
/// 获取页面总数
///
int TotalPages { get; }
///
/// Gets the current page items.
/// 获取当前页项
///
IList Items { get; }
///
/// Gets the has previous page.
/// 获取前一页
///
/// The has previous page.
bool HasPreviousPage { get; }
///
/// Gets the has next page.
/// 获取下一页
///
/// The has next page.
bool HasNextPage { get; }
}
}
新建文件: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; }
}
}
新建文件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
{
///
/// Http本地客户端
///
public class HttpRestClient
{
private readonly string? apiUrl;
protected readonly RestClient? client;
public HttpRestClient(string apiUrl)
{
this.apiUrl = apiUrl;
client = new RestClient();
}
///
/// 异步执行
///
///
///
public async Task 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(response.Content);
else
return new ApiResponse()
{
Status = false,
Result = null,
Message = response.ErrorMessage
};
}
public async Task> 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,
Message = "client为空"
};
//执行
var response = await client.ExecuteAsync(request);
//如果成功则执行序列化任务,否则返回失败代码
if (response.StatusCode == System.Net.HttpStatusCode.OK)
return JsonConvert.DeserializeObject>(response.Content);
else
return new ApiResponse()
{
Status = false,
Message = response.ErrorMessage
};
}
}
}
在HttpRestClient类中,因最新RestSharp版本为110,与老师不同,其中的RestRequest初始化流程也与老师给的不同,详细可在VS中参考github中给出的example。我在这里给出我的修改:https://www.cnblogs.com/dongxinya/p/17556221.html
PS:后续有问题,我还是回退到了老师的版本。
在我这里,当Request链接中的parameter的Search参数为空时,会返回失败,所以上述代码中增加了判断Search是否为空,为空则在请求中要删除Search参数。
新建文件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 where TEnity : class
{
Task> AddAsync(TEnity enity);
Task> UpdateAsync(TEnity enity);
Task DeleteAsync(int id );
Task> GetFirstOfDefaultAsync(int id);
Task>> GetAllAsync(QueryParameter parameter);
}
}
新建文件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 : IBaseService 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> AddAsync(TEnity enity)
{
BaseRequest request = new BaseRequest();
request.Method = RestSharp.Method.Post;
request.Route = $"api[{ServiceName}]/Add";
request.Parameter = enity;
return await client.ExecuteAsync(request);
}
///
/// 删除
///
///
///
public async Task 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>> 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>(request);
}
public async Task> GetFirstOfDefaultAsync(int id)
{
BaseRequest request = new BaseRequest();
request.Method = RestSharp.Method.Get;
request.Route = $"api/{ServiceName}/Get?id={id}";
return await client.ExecuteAsync(request);
}
public async Task> UpdateAsync(TEnity enity)
{
BaseRequest request = new BaseRequest();
request.Method = RestSharp.Method.Post;
request.Route = $"api/{ServiceName}/Update";
request.Parameter = enity;
return await client.ExecuteAsync(request);
}
}
}
新建文件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
{
}
}
新建文件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,ITodoService
{
private readonly HttpRestClient client;
public TodoService(HttpRestClient client):base (client,"Todo")
{
this.client = client;
}
public async Task>> 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>(request);
}
}
}
修改 文件:Mytodo/App.xaml.cs
部分修改为:
protected override void RegisterTypes(IContainerRegistry containerRegistry)
{
//注册服务
containerRegistry.GetContainer().Register(made: Parameters.Of.Type(serviceKey: "webUrl"));
containerRegistry.GetContainer().RegisterInstance(@"Http://localhost:19007/", serviceKey: "webUrl");
containerRegistry.Register();
containerRegistry.RegisterForNavigation();
containerRegistry.RegisterForNavigation();
containerRegistry.RegisterForNavigation();
containerRegistry.RegisterForNavigation();
containerRegistry.RegisterForNavigation();
containerRegistry.RegisterForNavigation();
containerRegistry.RegisterForNavigation();
}
修改文件:Mytodo/TodoViewModel.cs
private readonly ITodoService service;
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);
}
}
添加构造函数参数,并为参数赋值,同时调用写入UI函数
public TodoViewModel(ITodoService service)
{
TodoDtos=new ObservableCollection();
OpenRightContentCmd = new DelegateCommand(Add);
this.service = service;
//添加数据
CreateTodoList();
}