步步为盈
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

58 lines
2.6 KiB

using BBWY.Common.Http;
using BBWY.Common.Models;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Net.Http;
using Microsoft.Extensions.Configuration;
namespace BBWY.Client.APIServices
{
public class BaseApiService
{
private RestApiService restApiService;
protected GlobalContext globalContext;
public BaseApiService(RestApiService restApiService, GlobalContext globalContext)
{
this.restApiService = restApiService;
this.globalContext = globalContext;
}
protected ApiResponse<T> SendRequest<T>(string apiHost,
string apiPath,
object param,
IDictionary<string, string> headers,
HttpMethod httpMethod,
string contentType = RestApiService.ContentType_Json,
ParamPosition paramPosition = ParamPosition.Body,
bool enableRandomTimeStamp = false)
{
try
{
if (headers == null)
headers = new Dictionary<string, string>();
if (!headers.ContainsKey("ClientCode"))
headers.Add("ClientCode", "BBWY");
if (!headers.ContainsKey("ClientVersion"))
headers.Add("ClientVersion", "1.0.0.0");
if (!headers.ContainsKey("Authorization") && !string.IsNullOrEmpty(globalContext.UserToken))
headers.Add("Authorization", $"Bearer {globalContext.UserToken}");
if (!headers.ContainsKey("qy"))
headers.Add("qy", "qy");
var result = restApiService.SendRequest(apiHost, apiPath, param, headers, httpMethod, contentType, paramPosition, enableRandomTimeStamp);
if (result.StatusCode != System.Net.HttpStatusCode.OK &&
result.Content.Contains("\"Success\"") &&
result.Content.Contains("\"Msg\"") &&
result.Content.Contains("\"Data\""))
throw new BusinessException($"{result.StatusCode} {result.Content}") { Code = (int)result.StatusCode };
return JsonConvert.DeserializeObject<ApiResponse<T>>(result.Content);
}
catch (Exception ex)
{
return ApiResponse<T>.Error((ex is BusinessException) ? (ex as BusinessException).Code : 0, ex.Message);
}
}
}
}