Yc.Box.Types.Core
1.2.0
dotnet add package Yc.Box.Types.Core --version 1.2.0
NuGet\Install-Package Yc.Box.Types.Core -Version 1.2.0
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Yc.Box.Types.Core" Version="1.2.0" />
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Yc.Box.Types.Core" Version="1.2.0" />
<PackageReference Include="Yc.Box.Types.Core" />
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add Yc.Box.Types.Core --version 1.2.0
The NuGet Team does not provide support for this client. Please contact its maintainers for support.
#r "nuget: Yc.Box.Types.Core, 1.2.0"
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package Yc.Box.Types.Core@1.2.0
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=Yc.Box.Types.Core&version=1.2.0
#tool nuget:?package=Yc.Box.Types.Core&version=1.2.0
The NuGet Team does not provide support for this client. Please contact its maintainers for support.
Yc.Box.Types.Core
Основная библиотека типов для стандартизации API ответов в проектах YC. Предоставляет унифицированные модели для HTTP API ответов с поддержкой успешных операций, ошибок валидации и расширений для ASP.NET Core контроллеров.
🚀 Возможности
- Стандартизированные API ответы - Единообразные модели для всех HTTP API
- Встроенная поддержка ошибок - Автоматическая обработка ошибок валидации
- Расширения для контроллеров - Удобные методы для ASP.NET Core
- Типобезопасность - Полная поддержка типизированных ответов
- Совместимость - Работает с .NET 9.0+
📦 Установка
dotnet add package Yc.Box.Types.Core
🔧 Использование
Базовые API ответы
using Yc.Box.Types.Core.Models.ApiResponses;
// Успешный ответ
var successResponse = new YcApiResponse
{
Success = true,
Message = "Операция выполнена успешно"
};
// Ответ с данными
var dataResponse = new YcApiResponse<string>
{
Success = true,
Message = "Данные получены",
Data = "Результат операции"
};
Обработка ошибок
// Ошибка валидации
var validationError = new YcApiErrorResponse
{
Success = false,
StatusCode = 400,
Message = "Ошибка валидации",
Errors = new List<YcValidationError>
{
new YcValidationError
{
Field = "Email",
Message = "Неверный формат email",
AttemptedValue = "invalid-email"
}
}
};
// Ошибка "не найдено"
var notFoundError = new YcApiErrorResponse
{
Success = false,
StatusCode = 404,
Message = "Ресурс не найден"
};
Расширения для контроллеров
using Yc.Box.Types.Core.Models.ApiResponses;
[ApiController]
[Route("api/[controller]")]
public class UsersController : ControllerBase
{
[HttpGet]
public ActionResult<YcApiResponse<List<User>>> GetUsers()
{
var users = _userService.GetAll();
return this.SuccessResponse(users, "Пользователи получены");
}
[HttpGet("{id}")]
public ActionResult<YcApiResponse<User>> GetUser(int id)
{
var user = _userService.GetById(id);
if (user == null)
return this.NotFoundError($"Пользователь с ID {id} не найден");
return this.SuccessResponse(user);
}
[HttpPost]
public ActionResult<YcApiResponse<User>> CreateUser([FromBody] CreateUserRequest request)
{
if (!ModelState.IsValid)
return this.ValidationError();
var user = _userService.Create(request);
return this.SuccessResponse(user, "Пользователь создан");
}
[HttpPut("{id}")]
public ActionResult<YcApiResponse<User>> UpdateUser(int id, [FromBody] UpdateUserRequest request)
{
if (!ModelState.IsValid)
return this.ValidationError();
var user = _userService.Update(id, request);
if (user == null)
return this.NotFoundError($"Пользователь с ID {id} не найден");
return this.SuccessResponse(user, "Пользователь обновлен");
}
[HttpDelete("{id}")]
public ActionResult<YcApiResponse> DeleteUser(int id)
{
var success = _userService.Delete(id);
if (!success)
return this.NotFoundError($"Пользователь с ID {id} не найден");
return this.SuccessResponse("Пользователь удален");
}
}
Статические методы для создания ответов
using Yc.Box.Types.Core.Models.ApiResponses;
public class UserService
{
public YcApiResponse<List<User>> GetAllUsers()
{
try
{
var users = _repository.GetAll();
return YcApiResponseHelper.Success(users, "Пользователи получены");
}
catch (Exception ex)
{
return YcApiResponseHelper.InternalServerError("Ошибка при получении пользователей", ex.Message);
}
}
public YcApiErrorResponse ValidateUser(CreateUserRequest request)
{
var errors = new List<YcValidationError>();
if (string.IsNullOrEmpty(request.Email))
errors.Add(new YcValidationError { Field = "Email", Message = "Email обязателен" });
if (string.IsNullOrEmpty(request.Name))
errors.Add(new YcValidationError { Field = "Name", Message = "Имя обязательно" });
if (errors.Any())
return YcApiResponseHelper.ValidationError("Email", "Ошибка валидации", request.Email);
return null; // Нет ошибок
}
}
📋 Доступные методы расширения
Успешные ответы
SuccessResponse(message)
- Простой успешный ответSuccessResponse<T>(data, message)
- Успешный ответ с данными
Ошибки валидации
ValidationError()
- Ошибка на основе ModelStateValidationError(field, message, attemptedValue)
- Ошибка для конкретного поля
HTTP ошибки
NotFoundError(message)
- 404 ошибкаInternalServerError(message, details)
- 500 ошибкаUnauthorizedError(message)
- 401 ошибкаForbiddenError(message)
- 403 ошибкаCustomError(statusCode, message, details)
- Кастомная ошибка
🏗️ Структура пакета
Yc.Box.Types.Core/
└── Models/
└── ApiResponses/
├── YcApiResponse.cs # Базовый класс ответа
├── YcApiErrorResponse.cs # Класс ошибки
├── YcValidationError.cs # Детали ошибки валидации
├── YcApiResponseHelper.cs # Статические методы
└── YcControllerBaseExtensions.cs # Расширения контроллеров
🔒 Совместимость
- .NET 9.0+
- ASP.NET Core 9.0+
- Все классы имеют префикс
Yc
для избежания конфликтов имен
📄 Лицензия
Проект YC Team
🤝 Поддержка
Для вопросов и предложений обращайтесь к команде разработки YC.
📈 Версии
- 1.0.0 - Первоначальный релиз с базовыми API Response типами
- 1.1.0 - Добавлены расширения для контроллеров
- 1.2.0 - Переименование классов с префиксом Yc
Product | Versions Compatible and additional computed target framework versions. |
---|---|
.NET | net9.0 is compatible. net9.0-android was computed. net9.0-browser was computed. net9.0-ios was computed. net9.0-maccatalyst was computed. net9.0-macos was computed. net9.0-tvos was computed. net9.0-windows was computed. net10.0 was computed. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed. |
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.
-
net9.0
- No dependencies.
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.