net6 项目搭建及引用框架记录(log4net,autofac,exception,api result,jwt,efcore)五统一返回值格式
Posted 圆滚滚的胖狸
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了net6 项目搭建及引用框架记录(log4net,autofac,exception,api result,jwt,efcore)五统一返回值格式相关的知识,希望对你有一定的参考价值。
在项目Utility中建立文件夹ApiResult,先建立 ResultHelper文件
ResultHelper.cs
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using NET6Demo.IRepository;
namespace NET6Demo.Utility.ApiResult
public class ResultHelper
private readonly ILogger<ResultHelper> _logger;
private IResultModel _result;
public ResultHelper(ILogger<ResultHelper> logger, IResultModel result)
_logger = logger;
_result = result;
public IActionResult GetResult(int code, string msg = null, object value = null)
_result.StatusCode = code;
_result.Result = value;
if (string.IsNullOrWhiteSpace(msg))
if (code > 199 && code < 299)
_result.Message = "success";
else if (code > 399 && code < 499)
_result.Message = "error";
else if (code > 499 && code < 599)
_result.Message = "reject";
ObjectResult objResult = new ObjectResult(_result);
return objResult;
再建立ApiResultFilterAttribute.cs文件
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
namespace NET6Demo.Utility.ApiResult
public class ApiResultFilterAttribute : ActionFilterAttribute
private ResultHelper _result;
public ApiResultFilterAttribute(ResultHelper result)
_result = result;
public override void OnActionExecuting(ActionExecutingContext context)
base.OnActionExecuting(context);
public override void OnResultExecuting(ResultExecutingContext context)
var objectResult = context.Result as ObjectResult;
var code = objectResult != null ? objectResult.StatusCode : 500;
context.Result = _result.GetResult((int)code, string.Empty, objectResult.Value);
在Utility项目的Autofac中注册ResultHelper
//api返回值处理
container.RegisterType<ResultHelper>().InstancePerLifetimeScope();
在program.cs中添加统一返回值处理
#region 统一返回值
builder.Services.AddMvc(options =>
options.Filters.Add<ApiResultFilterAttribute>();
);
#endregion
//加在这句话的上面
var app = builder.Build();
在TestController中添加代码进行测试
运行代码,查看结果
再换一个返回值,再测试一次
到此统一返回值设置完毕。返回值内容可以根据项目需要再做修改
以上是关于net6 项目搭建及引用框架记录(log4net,autofac,exception,api result,jwt,efcore)五统一返回值格式的主要内容,如果未能解决你的问题,请参考以下文章
net6 项目搭建及引用框架记录(log4net,autofac,exception,api result,jwt,efcore)二配置log4net
net6 项目搭建及引用框架记录(log4net,autofac,exception,api result,jwt,efcore)六添加身份验证,引入JWT
net6 项目搭建及引用框架记录(log4net,autofac,exception,api result,jwt,efcore)六添加身份验证,引入JWT
net6 项目搭建及引用框架记录(log4net,autofac,exception,api result,jwt,efcore)六添加身份验证,引入JWT
net6 项目搭建及引用框架记录(log4net,autofac,exception,api result,jwt,efcore)一建立项目,使用Swagger
net6 项目搭建及引用框架记录(log4net,autofac,exception,api result,jwt,efcore)一建立项目,使用Swagger