Files
ASP.NET-CORE-web-test/Models/ResponseModels.cs
2025-10-10 16:02:38 +08:00

51 lines
1.7 KiB
C#
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

namespace SimpleTodoApiWithPg.Models
{
// 这是一个泛型记录 (generic record),用于包装所有 API 的返回数据
public record ApiResponse<T>(
bool Success,
string Message,
T? Data,
int Code = 200
);
// 提供一个静态类,方便快速创建标准响应
public static class ApiResponse
{
public static ApiResponse<T> Ok<T>(T data, string message = "操作成功")
{
return new ApiResponse<T>(true, message, data);
}
// **** 关键修改在这里:让 Fail 方法也变为泛型 ****
// 它接受一个类型参数 T并返回 ApiResponse<T>
// default(T) 对于引用类型(如 AuthResponse会返回 null
public static ApiResponse<T> Fail<T>(string message, int code = 400)
{
return new ApiResponse<T>(false, message, default(T), code);
}
// 您可以保留一个非泛型版本的 Fail 方便在某些无需特定 Data 类型的地方使用
// 但在需要特定返回类型的地方,请使用泛型版本
public static ApiResponse<object> Fail(string message, int code = 400)
{
return new ApiResponse<object>(false, message, null, code);
}
}
// 更新登录成功后返回的 DTO
public class AuthResponse
{
public string AccessToken { get; set; } = null!;
public string RefreshToken { get; set; } = null!;
public DateTime AccessTokenExpiration { get; set; }
}
public class RegisterResponse
{
public string? Username { get; set; }
public string? Email { get; set; }
public string? Password { get; set; }
public Guid UserId { get; set; }
}
}