Files
zszq-trs/Framework/YLErp.Core/Helpers/HttpHelper.cs
T
2024-05-09 14:06:26 +08:00

118 lines
3.6 KiB
C#

using RestSharp;
using RestSharp.Authenticators;
using RestSharp.Authenticators.OAuth2;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using YLErp.DBModels;
namespace YLErp.Helpers
{
public class HttpHelper
{
private string _baseUrl;
private Func<string> _tokenFunc;
public HttpHelper(string baseUrl, Func<string> tokenFunc = null)
{
_baseUrl = baseUrl;
_tokenFunc = tokenFunc;
}
public async Task<TResponse> PostRequest<TRequest, TResponse>(string apiPath, TRequest requestBody)
where TRequest : class
where TResponse : class
{
if (string.IsNullOrEmpty(_baseUrl))
{
throw new ServiceException("Web Base Url未配置");
}
// 创建RestClient
var client = new RestClient(_baseUrl);
if(_tokenFunc!=null)
{
client.Authenticator = new OAuth2AuthorizationRequestHeaderAuthenticator(_tokenFunc(), "Bearer");
}
// 设置token
if (_tokenFunc != null)
{
client.SetJwtToken(_tokenFunc());
}
// 创建请求参数
var request = new RestRequest(apiPath, Method.Post);
if (requestBody != null)
{
request.AddBody(requestBody);
}
// 发送请求并响应结果
var response = await client.ExecuteAsync<ReponseWrap<TResponse>>(request);
return response?.Data?.Data;
}
public async Task<TResponse> PostRequestNoAuth<TRequest, TResponse>(string apiPath, TRequest requestBody)
where TRequest : class
where TResponse : class
{
if (string.IsNullOrEmpty(_baseUrl))
{
throw new ServiceException("Web Base Url未配置");
}
// 创建RestClient
var client = new RestClient(_baseUrl);
// 创建请求参数
var request = new RestRequest(apiPath, Method.Post);
if (requestBody != null)
{
request.AddBody(requestBody);
}
// 发送请求并响应结果
var response = await client.ExecuteAsync<ReponseWrap<TResponse>>(request);
var responseContent = response.Content;
return Newtonsoft.Json.JsonConvert.DeserializeObject<TResponse>(responseContent);
}
public async Task<TResponse> GetRequestNoAuth<TResponse>(string apiPath)
where TResponse : class
{
if (string.IsNullOrEmpty(_baseUrl))
{
throw new ServiceException("Web Base Url未配置");
}
// 创建 RestClient
var client = new RestClient(_baseUrl);
// 创建请求参数
var request = new RestRequest(apiPath, Method.Get);
// 发送请求并获取响应结果
var response = await client.ExecuteAsync<ReponseWrap<TResponse>>(request);
var responseContent = response.Content;
return Newtonsoft.Json.JsonConvert.DeserializeObject<TResponse>(responseContent);
}
}
public static class RestClientExtension
{
public static void SetJwtToken(this RestClient restClient,string token)
{
restClient.Authenticator = new OAuth2AuthorizationRequestHeaderAuthenticator(token, "Bearer");
}
}
public class ReponseWrap<T>
{
public T Data { get; set; }
}
}