NetCore WebApi AOP统一返回值设计

实体

BaseResultModel
 public class BaseResultModel
    {
        public BaseResultModel(int? code = null, string message = null,
            object result = null, ReturnStatus returnStatus = ReturnStatus.Success)
        {
            this.Code = code;
            this.Result = result;
            this.Message = message;
            this.ReturnStatus = returnStatus;
        }

        public int? Code { get; set; }

        public string Message { get; set; }

        public object Result { get; set; }

        public ReturnStatus ReturnStatus { get; set; }
    }

    public enum ReturnStatus
    {
        Success = 1,
        Fail = 0,
        ConfirmIsContinue = 2,
        Error = 3
    }
ValidationFailedResult
  public class ValidationFailedResult : ObjectResult
    {
        public ValidationFailedResult(ModelStateDictionary modelState)
        : base(new ValidationFailedResultModel(modelState))
        {
            StatusCode = StatusCodes.Status422UnprocessableEntity;
        }
    }
ValidationFailedResultModel
 public class ValidationFailedResultModel : BaseResultModel
    {
        public ValidationFailedResultModel(ModelStateDictionary modelState)
        {
            Code = 422;
            Message = "参数不合法";
            Result = modelState.Keys.SelectMany(key => modelState[key].Errors.Select(x => new ValidationError(key, x.ErrorMessage))).ToList();
            ReturnStatus = ReturnStatus.Fail;
        }
    }

    public class ValidationError
    {
        [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
        public string Field { get; }

        public string Message { get; }

        public ValidationError(string field, string message)
        {
            Field = field != string.Empty ? field : null;
            Message = message;
        }
    }

过滤器

ApiResultFilterAttribute
 public class ApiResultFilterAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            base.OnActionExecuting(context);
        }

        public override void OnResultExecuting(ResultExecutingContext context)
        {
            if (context.Result is ValidationFailedResult)
            {
                var objectResult = context.Result as ObjectResult;
                context.Result = objectResult;
            }
            else
            {
                var objectResult = context.Result as ObjectResult;
                if (objectResult == null)
                {
                    context.Result = new OkObjectResult(null);
                }
                else
                {
                    context.Result = new OkObjectResult(objectResult.Value);
                }
            }
        }
    }
ErrorFilter
  public class ErrorFilter : ExceptionFilterAttribute
    {
        public override void OnException(ExceptionContext context)
        {
            if (context.ExceptionHandled == false)
            {
                string ip = context.HttpContext?.Connection.RemoteIpAddress.ToString();
                string Url = context.HttpContext.Request.Path;
                string Mthods = context.HttpContext.Request.Method;
                context.ExceptionHandled = true;
                context.HttpContext.Response.StatusCode = 500;
                ExecuteResult executeResult = new ExecuteResult();
                executeResult.SetFailMessage(context.Exception.Message);
                context.Result = new OkObjectResult(executeResult);
                
            }
        }
    }
ValidateModelAttribute
 public class ValidateModelAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            if (!context.ModelState.IsValid)
            {
                context.Result = new ValidationFailedResult(context.ModelState);
            }
        }

        public override void OnActionExecuted(ActionExecutedContext context)
        {
            base.OnActionExecuted(context);
        }
    }
 services.AddMvc(options =>
            {
                options.Filters.Add<ApiResultFilterAttribute>();
                options.Filters.Add<ValidateModelAttribute>();
                options.Filters.Add<ErrorFilter>();
            }

思考 如果我们这样的确确定了统一的返回值 但是又对代码有一定的入侵 是 统一返回好 还是说在控制器哪里创建返回值对象好呢?

你可能感兴趣的:(c#,常用的方法,.netcore)