-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathCommandWithResultController.cs
More file actions
55 lines (49 loc) · 2.21 KB
/
CommandWithResultController.cs
File metadata and controls
55 lines (49 loc) · 2.21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
namespace CommandQuery.AspNetCore
{
[ApiController]
[Route("api/command/[controller]")]
#pragma warning disable SA1649 // File name should match first type name
internal class CommandController<TCommand, TResult> : ControllerBase
#pragma warning restore SA1649 // File name should match first type name
where TCommand : ICommand<TResult>
{
private readonly ICommandProcessor _commandProcessor;
private readonly ILogger _logger;
/// <summary>
/// Initializes a new instance of the <see cref="CommandController{TCommand,TResult}"/> class.
/// </summary>
/// <param name="commandProcessor">An <see cref="ICommandProcessor"/>.</param>
/// <param name="logger">An <see cref="ILogger"/>.</param>
public CommandController(ICommandProcessor commandProcessor, ILogger<CommandController<TCommand, TResult>> logger)
{
_commandProcessor = commandProcessor;
_logger = logger;
}
/// <summary>
/// Handle a command.
/// </summary>
/// <param name="command">The command.</param>
/// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
/// <returns>The result for status code <c>200</c>, or an error for status code <c>400</c> and <c>500</c>.</returns>
[HttpPost]
public async Task<IActionResult> HandleAsync(TCommand command, CancellationToken cancellationToken)
{
if (_logger.IsEnabled(LogLevel.Information))
{
_logger.LogInformation("Handle {@Command}", command);
}
try
{
var result = await _commandProcessor.ProcessAsync(command, cancellationToken).ConfigureAwait(false);
return Ok(result);
}
catch (Exception exception)
{
_logger.LogError(exception, "Handle command failed: {@Command}", command);
return exception.IsHandled() ? BadRequest(exception.ToError()) : StatusCode(500, exception.ToError());
}
}
}
}