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