api管理器

This commit is contained in:
FalconFly 2024-04-15 16:08:49 +08:00
parent 9662da3139
commit 498913bb25
5 changed files with 309 additions and 0 deletions

View File

@ -0,0 +1,221 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Text.Encodings.Web;
using System.Text.Json;
using System.Text.Unicode;
using System.Threading.Tasks;
namespace Falcon.SugarApi.ApiManager
{
/// <summary>
/// api控制器基类
/// </summary>
[Area("api")]
[ApiController]
[Route("[Area]/[Controller]/[Action]")]
public abstract class ApiControllerBase:ControllerBase
{
/// <summary>
/// 日志记录服务
/// </summary>
public ILogger Logger { get; set; }
/// <summary>
/// 服务集合
/// </summary>
public IServiceProvider Services { get; set; }
/// <summary>
/// 应用程序跟目录
/// </summary>
public string AppPath => AppDomain.CurrentDomain.BaseDirectory;
/// <summary>
/// 请求的控制器名称
/// </summary>
public string? ControllerName => this.RouteData.Values["controller"]?.ToString();
/// <summary>
/// 请求的方法名称
/// </summary>
public string? ActionName => this.RouteData.Values["action"]?.ToString();
/// <summary>
/// 构造控制器基类
/// </summary>
/// <param name="service"></param>
protected ApiControllerBase(IServiceProvider service) {
this.Services = service;
this.Logger = service.GetService(typeof(ILogger<>).MakeGenericType(GetType())) as ILogger ?? throw new NullReferenceException("ILogger");
}
#region
/// <summary>
/// 记录信息日志
/// </summary>
/// <param name="msg">信息文本</param>
protected virtual void SaveLog(string msg) => this.Logger.LogInformation($"信息:{msg}");
/// <summary>
/// 记录错误日志
/// </summary>
/// <param name="err">错误信息</param>
protected virtual void SaveLogError(string err) => this.Logger.LogError($"错误:{err}");
/// <summary>
/// 记录异常日志
/// </summary>
/// <param name="ex">异常信息</param>
protected virtual void SaveLogException(Exception ex) => this.Logger.LogCritical($"异常:{ex}");
/// <summary>
/// 保存log日志
/// </summary>
/// <param name="context">数据上下文</param>
protected virtual void SaveLog(LoggerContext context) {
if(context == null) {
return;
}
var sb = new StringBuilder();
sb.AppendLine($"接收到的数据:{context.Data}");
sb.AppendLine($"返回结果:{context.Result}");
sb.AppendLine($"异常:{context.Exception}");
if(context.Exception == "") {
this.Logger.LogInformation(sb.ToString());
}
else {
this.Logger.LogError(sb.ToString());
}
}
/// <summary>
/// 保存请求日志
/// </summary>
/// <typeparam name="TData">请求数据类型</typeparam>
/// <typeparam name="TResult">返回的数据类型</typeparam>
/// <param name="data">请求的数据</param>
/// <param name="result">返回的数据</param>
/// <param name="exception">执行过程中异常</param>
protected virtual void SaveLog<TData, TResult>(TData? data,TResult? result,Exception? exception = null) {
var context = new LoggerContext();
context.Data = data == null ? "" : this.JsonSerialize(data);
context.Result = result == null ? "" : this.JsonSerialize(result);
context.Exception = exception == null ? "" : exception.ToString();
SaveLog(context);
}
#endregion
#region
/// <summary>
/// 从对象序列化字符串
/// </summary>
/// <typeparam name="T">对象类型</typeparam>
/// <param name="obj">要序列化的对象</param>
/// <returns>字符串</returns>
protected string JsonSerialize<T>(T obj) {
return JsonSerializer.Serialize<T>(obj,new JsonSerializerOptions {
Encoder = JavaScriptEncoder.Create(UnicodeRanges.All),
});
}
/// <summary>
/// 从字符串反序列化对象
/// </summary>
/// <typeparam name="T">对象的类型</typeparam>
/// <param name="json">json字符串</param>
/// <returns>对象实例</returns>
protected T? JsonDeserialize<T>(string json) where T : class {
return JsonSerializer.Deserialize<T>(json);
}
#endregion
#region
/// <summary>
/// 验证对象的所有属性是否满足定义
/// </summary>
/// <param name="value">要验证的对象的值</param>
/// <returns></returns>
protected virtual (bool isValid, List<ValidationResult>? failProps) ModelValidation(object? value) {
if(value == null) return (false, null);
var context = new ValidationContext(value);
var validations = new List<ValidationResult>();
var r = Validator.TryValidateObject(value,context,validations,true);
return (r, validations);
}
#endregion
#region
/// <summary>
/// 同步返回成功的结果
/// </summary>
/// <typeparam name="T">data携带的数据类型</typeparam>
/// <param name="resultBuilder">返回结果创建者</param>
/// <returns>同步api结果</returns>
protected virtual ApiResult<T> SuccessResult<T>(Action<ApiResult<T>>? resultBuilder) {
var result = new ApiResult<T> {
Code = 0,Msg = ""
};
resultBuilder?.Invoke(result);
return result;
}
/// <summary>
/// 同步返回成功的结果
/// </summary>
/// <typeparam name="T">data携带的数据类型</typeparam>
/// <param name="result">携带数据</param>
/// <returns>同步api结果</returns>
protected virtual ApiResult<T> SuccessResult<T>(T result)
=> SuccessResult<T>(b => b.Data = result);
/// <summary>
/// 异步返回成功的结果
/// </summary>
/// <typeparam name="T">data携带的数据类型</typeparam>
/// <param name="result">携带数据</param>
/// <returns>异步api结果</returns>
protected virtual async Task<ApiResult<T>> SuccessResultAsync<T>(T result)
=> await Task.FromResult(SuccessResult(result));
/// <summary>
/// 同步返回失败的结果
/// </summary>
/// <typeparam name="T">data携带的数据类型</typeparam>
/// <param name="failResultBuilder">失败信息创建器</param>
/// <returns>异步api结果</returns>
protected virtual ApiResult<T> FailResult<T>(Action<ApiResult<T>>? failResultBuilder) {
var result = new ApiResult<T> { Code = 1 };
failResultBuilder?.Invoke(result);
return result;
}
/// <summary>
/// 同步返回失败的结果
/// </summary>
/// <typeparam name="T">data携带的数据类型</typeparam>
/// <param name="failMessage">失败信息</param>
/// <returns>异步api结果</returns>
protected virtual ApiResult<T> FailResult<T>(string failMessage)
=> FailResult<T>(b => b.Msg = failMessage);
/// <summary>
/// 同步返回失败的结果
/// </summary>
/// <typeparam name="T">data携带的数据类型</typeparam>
/// <param name="exception">异常</param>
/// <returns>异步api结果</returns>
protected virtual ApiResult<T> FailResult<T>(Exception exception)
=> FailResult<T>(b => {
b.Msg = "运行发生异常";
b.Exception = exception.ToString();
});
#endregion
}
}

View File

@ -0,0 +1,9 @@
namespace Falcon.SugarApi.ApiManager
{
/// <summary>
/// Api请求
/// </summary>
public class ApiRequest
{
}
}

View File

@ -0,0 +1,35 @@
using System.Text.Json.Serialization;
namespace Falcon.SugarApi.ApiManager
{
/// <summary>
/// api返回结果
/// </summary>
/// <typeparam name="T">携带的数据类型</typeparam>
public class ApiResult<T>
{
/// <summary>
/// 结果代码 0成功 1失败
/// </summary>
[JsonPropertyName("code")]
public int Code { get; set; }
/// <summary>
/// 失败信息
/// </summary>
[JsonPropertyName("msg")]
public string Msg { get; set; }
/// <summary>
/// 程序发生的异常
/// </summary>
public string? Exception { get; set; }
/// <summary>
/// 分页结果。如果为null则为未分页
/// </summary>
public PageResult? Paging { get; set; }
/// <summary>
/// 携带数据
/// </summary>
[JsonPropertyName("data")]
public T? Data { get; set; }
}
}

View File

@ -0,0 +1,21 @@
namespace Falcon.SugarApi.ApiManager
{
/// <summary>
/// api日志上下文
/// </summary>
public class LoggerContext
{
/// <summary>
/// 接收数据
/// </summary>
public string? Data { get; set; }
/// <summary>
/// 返回结果
/// </summary>
public string? Result { get; set; }
/// <summary>
/// 执行异常
/// </summary>
public string? Exception { get; set; }
}
}

View File

@ -0,0 +1,23 @@

namespace Falcon.SugarApi.ApiManager
{
/// <summary>
/// 数据分页结果
/// </summary>
public class PageResult
{
/// <summary>
/// 页号码。从1开始
/// </summary>
public int Page { get; set; } = 1;
/// <summary>
/// 页大小
/// </summary>
public int PageSize { get; set; } = 50;
/// <summary>
/// 总数据数
/// </summary>
public int Count { get; set; } = 0;
}
}