为API增加成功和失败返回方法。

This commit is contained in:
falcon 2023-03-14 16:14:12 +08:00
parent 96beff6a1c
commit 74ef5a4c7b
2 changed files with 100 additions and 8 deletions

View File

@ -1,4 +1,5 @@
using Falcon.SugarApi.DatabaseDefinitions; using Falcon.SugarApi.DatabaseDefinitions;
using Falcon.SugarApi.ModelValidation;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
@ -6,6 +7,7 @@ using System;
using System.Text.Encodings.Web; using System.Text.Encodings.Web;
using System.Text.Json; using System.Text.Json;
using System.Text.Unicode; using System.Text.Unicode;
using System.Threading.Tasks;
namespace Falcon.SugarApi.ApiDefinistions namespace Falcon.SugarApi.ApiDefinistions
{ {
@ -15,7 +17,7 @@ namespace Falcon.SugarApi.ApiDefinistions
[Area("api")] [Area("api")]
[ApiController] [ApiController]
[Route("[Area]/[Controller]/[Action]")] [Route("[Area]/[Controller]/[Action]")]
public abstract class ApiControllerBase : ControllerBase public abstract class ApiControllerBase:ControllerBase
{ {
/// <summary> /// <summary>
/// 日志记录服务 /// 日志记录服务
@ -55,6 +57,8 @@ namespace Falcon.SugarApi.ApiDefinistions
this.SugarDb = service.GetService<SugarDbContext>() ?? throw new NullReferenceException("SugarDbContext"); this.SugarDb = service.GetService<SugarDbContext>() ?? throw new NullReferenceException("SugarDbContext");
} }
#region
/// <summary> /// <summary>
/// 保存文本日志 /// 保存文本日志
/// </summary> /// </summary>
@ -69,7 +73,7 @@ namespace Falcon.SugarApi.ApiDefinistions
/// <param name="data">请求数据</param> /// <param name="data">请求数据</param>
/// <param name="result">响应数据</param> /// <param name="result">响应数据</param>
/// <param name="exception">异常</param> /// <param name="exception">异常</param>
protected virtual void SaveLogger<TRequest, TResponse>(TRequest data, TResponse result, Exception? exception = null) { protected virtual void SaveLogger<TRequest, TResponse>(TRequest data,TResponse result,Exception? exception = null) {
var requestStr = this.JsonSerialize(data); var requestStr = this.JsonSerialize(data);
var responseStr = this.JsonSerialize(result); var responseStr = this.JsonSerialize(result);
var exStr = exception == null ? "" : exception.ToString(); var exStr = exception == null ? "" : exception.ToString();
@ -77,6 +81,9 @@ namespace Falcon.SugarApi.ApiDefinistions
this.Logger.LogInformation(logmsg); this.Logger.LogInformation(logmsg);
} }
#endregion
/// <summary> /// <summary>
/// 从对象序列化字符串 /// 从对象序列化字符串
/// </summary> /// </summary>
@ -84,7 +91,7 @@ namespace Falcon.SugarApi.ApiDefinistions
/// <param name="obj">要序列化的对象</param> /// <param name="obj">要序列化的对象</param>
/// <returns>字符串</returns> /// <returns>字符串</returns>
protected string JsonSerialize<T>(T obj) { protected string JsonSerialize<T>(T obj) {
return JsonSerializer.Serialize<T>(obj, new JsonSerializerOptions { return JsonSerializer.Serialize<T>(obj,new JsonSerializerOptions {
Encoder = JavaScriptEncoder.Create(UnicodeRanges.All), Encoder = JavaScriptEncoder.Create(UnicodeRanges.All),
}); });
} }
@ -98,14 +105,29 @@ namespace Falcon.SugarApi.ApiDefinistions
return JsonSerializer.Deserialize<T>(json); return JsonSerializer.Deserialize<T>(json);
} }
/// <summary>
/// 验证模型。如果失败抛出异常
/// </summary>
/// <param name="model">模型</param>
protected virtual void ModelValidation(object? model) {
model.ThrowNullExceptionWhenNull();
if(!model.TryModelValidation(out var errors)) {
ThrowApiException("传入的数据验证错误",null,e => {
e.Data.Add("ModelValidation",errors);
});
}
}
#region
/// <summary> /// <summary>
/// 抛出api异常 /// 抛出api异常
/// </summary> /// </summary>
/// <param name="msg">异常消息</param> /// <param name="msg">异常消息</param>
/// <param name="innException">内部异常</param> /// <param name="innException">内部异常</param>
/// <exception cref="ApiException">api异常</exception> /// <exception cref="ApiException">api异常</exception>
protected virtual void ThrowApiException(string msg, Exception innException) protected virtual void ThrowApiException(string msg,Exception innException)
=> throw new ApiException(msg, innException); => throw new ApiException(msg,innException);
/// <summary> /// <summary>
/// 抛出api异常 /// 抛出api异常
/// </summary> /// </summary>
@ -119,7 +141,7 @@ namespace Falcon.SugarApi.ApiDefinistions
/// <param name="innException">内部异常</param> /// <param name="innException">内部异常</param>
/// <exception cref="ApiException">api异常</exception> /// <exception cref="ApiException">api异常</exception>
protected virtual void ThrowApiException(Exception innException) protected virtual void ThrowApiException(Exception innException)
=> throw new ApiException(innException.Message, innException); => throw new ApiException(innException.Message,innException);
/// <summary> /// <summary>
/// 抛出api异常 /// 抛出api异常
@ -127,10 +149,53 @@ namespace Falcon.SugarApi.ApiDefinistions
/// <param name="msg">异常消息</param> /// <param name="msg">异常消息</param>
/// <param name="innException">内部异常</param> /// <param name="innException">内部异常</param>
/// <param name="exAction">异常处理方法</param> /// <param name="exAction">异常处理方法</param>
protected virtual void ThrowApiException(string msg, Exception innException, Action<ApiException> exAction) { protected virtual void ThrowApiException(string msg,Exception innException,Action<ApiException> exAction) {
var ex = new ApiException(msg, innException); var ex = new ApiException(msg,innException);
exAction?.Invoke(ex); exAction?.Invoke(ex);
throw ex; throw ex;
} }
#endregion
#region api调用结果
/// <summary>
/// 同步返回成功的结果
/// </summary>
/// <typeparam name="T">data携带的数据类型</typeparam>
/// <param name="result">携带数据</param>
/// <returns>异步api结果</returns>
protected virtual ApiResult<T> SuccessResult<T>(T result)
=> new() { Code = 0,Msg = "",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="failMessage">失败信息</param>
/// <returns>异步api结果</returns>
protected virtual ApiResult<T> FailResult<T>(string failMessage)
=> new() { Code = 1,Msg = failMessage,};
/// <summary>
/// 异步返回失败的结果
/// </summary>
/// <typeparam name="T">data携带的数据类型</typeparam>
/// <param name="failMessage">失败信息</param>
/// <returns>异步api结果</returns>
protected virtual async Task<ApiResult<T>> FailResultAsync<T>(string failMessage)
=> await Task.FromResult(FailResult<T>(failMessage));
#endregion
} }
} }

View File

@ -0,0 +1,27 @@
using System.Text.Json.Serialization;
namespace Falcon.SugarApi.ApiDefinistions
{
/// <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>
[JsonPropertyName("data")]
public T? Data { get; set; }
}
}