WPF怎么通过RestSharp向后端发请求
1.下载RestSharpNuGet包
2.请求类和响应类
public class ApiRequest
{
/// <summary>
/// 请求地址
/// </summary>
public string Route { get; set; }
/// <summary>
/// 请求方式
/// </summary>
public Method Method { get; set; }
/// <summary>
/// 请求参数
/// </summary>
public Object Parameters { get; set; }
/// <summary>
/// 请求头,表示发送的请求的类型、数据格式等
/// </summary>
public string ContentType { get; set; } = "application/json";
}
public class ApiResponse
{
public int Code { get; set; }
public string Msg { get; set; }
public Object Data { get; set; }
}
3.封装请求工具类
public class HttpClient
{
private readonly RestClient Client; // 客户端
private readonly string baseUrl = "http://localhost:63615/api/";
public HttpClient()
{
Client = new RestClient();
}
/// <summary>
/// 执行请求
/// </summary>
/// <param name="request">请求数据</param>
/// <returns>响应数据</returns>
public ApiResponse Execute(ApiRequest ApiRequest)
{
var request = new RestRequest(ApiRequest.Method);
request.AddHeader("Content-Type", ApiRequest.ContentType);
if (ApiRequest.Parameters!= null)
{
// SerializeObject 序列化参数 object -> json
request.AddParameter("params", JsonConvert.SerializeObject(ApiRequest.Parameters), ParameterType.RequestBody);
}
// 设置请求地址
Client.BaseUrl = new Uri(baseUrl + ApiRequest.Route);
// 发送请求
var res = Client.Execute(request);
if (res.StatusCode == System.Net.HttpStatusCode.OK)
{
// 反序列化响应数据 json -> object
return JsonConvert.DeserializeObject<ApiResponse>(res.Content);
}
else
{
return new ApiResponse { Code = (int)res.StatusCode, Msg = res.ErrorMessage };
}
}
}
4. 在接口中引入该类,并在构造函数中初始化
private readonly IEventAggregator _eventAggregator;
public LoginUCViewModel(HttpClient httpClient)
{
//请求Client
_httpClient = httpClient;
}
5.发送请求
// 发送请求
ApiRequest apiRequest = new ApiRequest();
// 请求方式
apiRequest.Method = RestSharp.Method.POST;
// 请求地址(这里只写这一段是因为定义的时候定义了baseUrl
apiRequest.Route = "Account/Register";
AccountInfoDto.Password = Md5Helper.GetMd5(AccountInfoDto.Password);
apiRequest.Parameters = AccountInfoDto;
ApiResponse response = _httpClient.Execute(apiRequest);
到此,简单的请求封装就结束了