using Microsoft.AspNetCore.Mvc; using System.ComponentModel.DataAnnotations; using System.Text.Json.Serialization; namespace Blahblah.FlowerStory.Server.Controller; partial class BaseController { private static ErrorResponse CreateErrorResponse(int status, string title, string? detail = null, string? instance = null) { return new ErrorResponse { Status = status, Title = title, Detail = detail, Instance = instance }; } /// /// 用户未找到 /// protected new NotFoundObjectResult NotFound() { return NotFound("User not found"); } /// /// 发生了未找到的错误 /// /// /// /// protected NotFoundObjectResult NotFound(string title, string? detail = null, string? instance = null) { return NotFound(CreateErrorResponse(StatusCodes.Status404NotFound, title, detail, instance)); } /// /// 授权异常 /// protected new UnauthorizedObjectResult Unauthorized() { return Unauthorized("Unauthorized"); } /// /// 发生了未授权的错误 /// /// /// /// protected UnauthorizedObjectResult Unauthorized(string title, string? detail = null, string? instance = null) { return Unauthorized(CreateErrorResponse(StatusCodes.Status401Unauthorized, title, detail, instance)); } } /// /// 错误结果 /// public record ErrorResponse { /// /// 错误代码 /// [Required] public required int Status { get; init; } /// /// 错误标题 /// [Required] public required string Title { get; init; } /// /// 错误详细信息 /// [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] public string? Detail { get; init; } /// /// 错误示例 /// [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] public string? Instance { get; init; } }