// namespace SafeCampus.Core; /// /// 规范化RESTful风格返回值 /// [SuppressSniffer] [UnifyModel(typeof(SafeCampusResult<>))] public class SafeCampusResultProvider : IUnifyResultProvider { public IActionResult OnAuthorizeException(DefaultHttpContext context, ExceptionMetadata metadata) { return new JsonResult(ResTfulResult(metadata.StatusCode, data: metadata.Data, errors: metadata.Errors), UnifyContext.GetSerializerSettings(context)); } /// /// 异常返回 /// /// /// /// public IActionResult OnException(ExceptionContext context, ExceptionMetadata metadata) { return new JsonResult(ResTfulResult(metadata.StatusCode, data: metadata.Data, errors: metadata.Errors)); } /// /// 成功返回 /// /// /// /// public IActionResult OnSucceeded(ActionExecutedContext context, object data) { return new JsonResult(ResTfulResult(StatusCodes.Status200OK, true, data)); } /// /// 验证失败返回 /// /// /// /// public IActionResult OnValidateFailed(ActionExecutingContext context, ValidationMetadata metadata) { return new JsonResult(ResTfulResult(metadata.StatusCode ?? StatusCodes.Status400BadRequest, data: metadata.Data, errors: metadata.FirstErrorMessage ?? metadata.Message)); } /// /// 状态码响应拦截 /// /// /// /// /// public async Task OnResponseStatusCodes(HttpContext context, int statusCode, UnifyResultSettingsOptions unifyResultSettings = null) { // 设置响应状态码 UnifyContext.SetResponseStatusCodes(context, statusCode, unifyResultSettings); switch (statusCode) { // 处理 401 状态码 case StatusCodes.Status401Unauthorized: await context.Response.WriteAsJsonAsync(ResTfulResult(statusCode, errors: "登录已过期,请重新登录"), App.GetOptions()?.JsonSerializerOptions); break; // 处理 403 状态码 case StatusCodes.Status403Forbidden: await context.Response.WriteAsJsonAsync(ResTfulResult(statusCode, errors: "禁止访问,没有权限", data: context.Request.Path), App.GetOptions()?.JsonSerializerOptions); break; } } /// /// 返回 RESTful 风格结果集 /// /// 状态码 /// 是否成功 /// 数据 /// 错误信息 /// private static SafeCampusResult ResTfulResult(int statusCode, bool succeeded = default, object data = default, object errors = default) { return new SafeCampusResult { Code = statusCode, Msg = statusCode == StatusCodes.Status200OK ? "请求成功" : errors, Data = data, Extras = UnifyContext.Take(), Time = DateTime.Now }; } }