using YYApi.Communications; using YYApi.Helpers; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Filters; using Microsoft.AspNetCore.Mvc.ModelBinding; using System.Linq; namespace YYApi.Controllers { /// /// 基础控制器,所有控制器均继承本控制器 /// 1. 自动验证请求参数 /// 2. 报错返回 /// 3. 错误回馈页面 /// public class BaseController : Controller { /// /// 当前登录用户的ID /// protected LoginInfoItem LoginInfo => (LoginInfoItem)HttpContext.Items["LoginInfo"]; /// /// 验证请求参数 /// /// public override void OnActionExecuting(ActionExecutingContext context) { if (!context.ModelState.IsValid) { foreach (var item in context.ModelState.Values) { if (item.ValidationState == ModelValidationState.Invalid) { Error(400, item.Errors.First().ErrorMessage); break; } } } } /// /// 错误返回 /// /// 错误代码 /// 错误描述(若是常规错误,代码可自动带取描述) /// protected static void Error(int code, string message = "") { throw new ApiException(code, message); } /// /// 检测条件,根据条件返回报错 /// /// 检测条件 /// 错误代码 /// 错误描述 protected static void ErrorWhen(bool condition, int code, string message = "") { if (condition) { Error(code, message); } } /// /// 检测给定的变量是否为NUll /// /// 检测条件 /// 错误代码 /// 错误描述 protected static void ErrorWhenNull(object condition, int code, string message = "") { ErrorWhen(condition == null, code, message); } /// /// 错误回馈页面 /// /// 错误代码 /// [HttpGet("exception/{code:int}")] [ApiExplorerSettings(IgnoreApi = true)] public BaseResponse ExceptionHandler(int code) { var response = new BaseResponse(); response.SetCode(code); return response; } protected BaseResponse UploadFile() { return new BaseResponse(); } } }