Wiki
Clone wikiWeb API Spike / Creating Command Handlers
Creating Command Handlers
Create the command handler class file and write three classes TestCommand
, TestCommandRequest
and RequestValidator
like so;
#!csharp namespace Web_API_Spike.Commands { [Validator(typeof(RequestValidator))] public class TestCommandRequest : IRequest<string> { public string Message; public class RequestValidator : AbstractValidator<TestCommandRequest> { public RequestValidator() { RuleFor(r => r.Message).NotEmpty().WithMessage("message cannot be empty"); } } } public class TestCommand: IRequestHandler<TestCommandRequest, string> { public string Handle(TestCommandRequest message) { return message.Message; } } }
In the controller, specify a POST route like this;
#!csharp [HttpPost] [Route("echo")] public IHttpActionResult Echo(TestCommandRequest request) { var echoMessage = _mediator.Send(request); return Ok(new { Message = echoMessage }); }
Web API will run your validation against the request
object before this route is hit against the rule specified and return before the route is hit. If the request
validates, then it will call the Echo
method. The request is then dispatched synchronously with the mediator which will cause the command handler to be called. There is also a SendAsync()
method on the mediator for longer running requests.
Updated