Что заставляет мой разум щекотать, это решение, которое мне нужно принять, и компромисс, который он приносит. Если я решу, что сервис будет выбрасывать исключение, которое делает код чище, потому что сервис не зависит от абстракций основных абстракций ASP.NET, таких как iActionResult и NotFoundObjectResult . Тем не менее, метание исключения - это дорогостоящая операция, и серверу требуется больше времени, чтобы обработать его, чем простой объект возвращает.
С другой Операция, она делает вещи быстрее в случае ошибки, но она объединяет службу с типами ядра ASP.NET. Используйте.
Код: Выделить всё
[Route("api/users")]
[ApiController]
public class UsersController : ControllerBase
{
// ... unimportant code
[HttpDelete("{id}")]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task DeleteUser([Required] string id)
{
if (!ModelState.IsValid)
{
return BadRequest();
}
await userManagementService.DeleteUser(id); // all logic inside this service method
return NoContent();
}
}
Код: Выделить всё
public class UserManagementService : IUserManagementService
{
// ... unimportant code
public Task DeleteUser(string id)
{
var user = await _dbContext.Users.FindAsync(id);
if (user == null)
{
throw new MyNotFoundException($"User with id: {id} not found");
}
// ... code that deletes the user and cleanups all resources associated
// with it (eg. things not just in the db but also user files on the content server)
}
}
< /code>
подход с возвращением iActionResult < /h3>
[Route("api/users")]
[ApiController]
public class UsersController : ControllerBase
{
// ... unimportant code
[HttpDelete("{id}")]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task DeleteUser([Required] string id)
{
if (!ModelState.IsValid)
{
return BadRequest();
}
return await userManagementService.DeleteUser(id); // all logic inside this service method
}
}
Код: Выделить всё
public class UserManagementService : IUserManagementService
{
// ... unimportant code
public Task DeleteUser(string id)
{
var user = await _dbContext.Users.FindAsync(id);
if (user == null)
{
return new NotFoundObjectResult($"User with id: {id} not found");
}
// ... code that deletes the user and cleanups all resources associated
// with it (eg. things not just in the db but also user files on the content server)
// ... success
new NoContentResult();
}
}
Подробнее здесь: https://stackoverflow.com/questions/766 ... t-core-web