.net core 数据统一响应分享
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了.net core 数据统一响应分享,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含4146字,纯文字阅读大概需要6分钟。
内容图文
![.net core 数据统一响应分享](/upload/InfoBanner/zyjiaocheng/1135/21ef63e7eff04cce985032bc9043a7ef.jpg)
前言
代码胡乱写,维护火葬场!
在平时工作中遇到前同事写接口这样返回值
当接口返回1时,不去看他的代码就永远猜不到这个1代表的是返回成功还是返回值
稍微好点的
维护和改bug简直让人疯狂,导致大部分时间浪费在“体会”别人返回值的逻辑中
天天加班与救bug于水火之中
合理分配前后端返回值很重要!
一般我们常用统一的格式返回json,无论后台是运行正常还是发生异常,响应给前端的数据格式是不变的!
publicclassResult<T> whereT : class
{
public ResultCode code { get; set; }
publicstring msg { get; set; }
public T data { get; set; }
}
包装一下,通常使用构造函数
publicclassResult<T> whereT : class
{
public ResultCode code { get; set; }
publicstring msg { get; set; }
public T data { get; set; }
publicResult(T data)
{
code = ResultCode.Ok;
msg = ResultCode.Ok.GetDescription();
this.data = data;
}
publicResult(ResultCode code, string msg, T data)
{
this.code = code;
this.msg = msg ?? code.GetDescription();
this.data = data;
}
}
这么使用new Result<Store>(code, msg, data)
使用起来还是不够简化
继续封装
publicclassResult<T> whereT : class
{
public ResultCode code { get; set; }
publicstring msg { get; set; }
public T data { get; set; }
publicResult(T data)
{
code = ResultCode.Ok;
msg = ResultCode.Ok.GetDescription();
this.data = data;
}
publicResult(ResultCode code, string msg, T data)
{
this.code = code;
this.msg = msg ?? code.GetDescription();
this.data = data;
}
publicstatic Result<T> FromCode(ResultCode code, string msg = null, T data = default)
{
if (data == null)
data = (T) new Object();
returnnew Result<T>(code, msg, data);
}
publicstatic Result<T> Ok(T data)
{
returnnew Result<T>(data);
}
publicstatic Result<T> FromError(ResultCode code = ResultCode.Fail, string msg = null, T data = default)
{
returnnew Result<T>(code, msg, data);
}
}
[HttpGet]
public Result<Store> Get()
{
return Result<Store>.Ok(new Store());
}
这样就稍微好点了
全局处理响应数据
虽然控制器返回值可以统一了,但是异常处理并没有统一,这时候就需要建个中间件/异常过滤器进行处理异常
app.UseMiddleware<GlobalExceptionHandlerMiddleware>();
publicclassGlobalExceptionHandlerMiddleware
{
privatereadonly RequestDelegate _next;
publicGlobalExceptionHandlerMiddleware(RequestDelegate next)
{
_next = next;
}
publicasync Task Invoke(HttpContext context)
{
try
{
await _next(context);
}
catch (System.Exception ex)
{
context.Response.StatusCode = 500;
context.Response.ContentType = "text/json;charset=utf-8;";
if (ex is ResultException == false)
{
var logger = context.RequestServices.GetRequiredService<ILoggerFactory>().CreateLogger<GlobalExceptionHandlerMiddleware>();
logger.LogError(1, ex, ex.Message);
}
var json = Result<object>.FromCode(ResultCode.Fail, ex.Message);
var error = JsonSerializer.Serialize(json);
await context.Response.WriteAsync(error);
}
}
}
有些异常是不需要记录的,这时候可以自定义ResultException
进行判断
publicclassResultException : Exception
{
publicResultException(string message) : base(message)
{
}
publicResultException(string message, Exception e) : base(message, e)
{
}
}
if (ex is ResultException == false)
{
var logger = context.RequestServices.GetRequiredService<ILoggerFactory>().CreateLogger<GlobalExceptionHandlerMiddleware>();
logger.LogError(1, ex, ex.Message);
}
参数校验处理
一个接口一般对参数(请求数据)都会进行安全校验,按照之前的格式返回验证异常。
publicclassModelActionFilter : ActionFilterAttribute, IActionFilter
{
publicoverridevoidOnActionExecuting(ActionExecutingContext context)
{
if (!context.ModelState.IsValid)
{
var errorResults = new List<ErrorResultDto>();
foreach (var item in context.ModelState)
{
var result = new ErrorResultDto
{
Field = item.Key,
Msg = "",
};
foreach (var error in item.Value.Errors)
{
if (!string.IsNullOrEmpty(result.Msg))
{
result.Msg += ‘|‘;
}
result.Msg += error.ErrorMessage;
}
errorResults.Add(result);
}
context.Result = new JsonResult(Result<List<ErrorResultDto>>.FromCode(ResultCode.InvalidData, data: errorResults));
}
}
}
publicclassErrorResultDto
{
///<summary>/// 参数领域///</summary>publicstring Field { get; set; }
///<summary>/// 错误信息///</summary>publicstring Msg { get; set; }
}
Startup.cs
services.AddControllers(options =>
{
options.Filters.Add(new ModelActionFilter());
options.MaxModelValidationErrors = 50;
options.ModelBindingMessageProvider.SetValueMustNotBeNullAccessor(
_ => "该字段不可为空。");
})
原文:https://www.cnblogs.com/lonelyxmas/p/13028722.html
内容总结
以上是互联网集市为您收集整理的.net core 数据统一响应分享全部内容,希望文章能够帮你解决.net core 数据统一响应分享所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。