Search code examples
asp.net-mvcasp.net-core-3.1cqrsmediator

How to validate CQRS query


I'm working on an APS.NET Core MVC Web application and I have two questions.

  1. How can I validate (using FluentValidation) a CQRS query before executing?
  2. ​How can I redirect a user to the error page (e.g. 404 page) when FluentValidation failed?

First question description

Without CQRS I use the following method to get a tag by ID and if the tag not found it simply returns not found result:

public async Task<IActionResult> Edit(int id)
{
    var tag = await _unitOfWork.Tags.GetAsync(id);
    if (tag is null)
        return NotFound();

    return View(tag);
}

With CQRS I use the following code:

// CQRS Query
public class GetTagByIdQuery : IRequest<Tag>
{
    public int Id { get; set; }

    public class GetTagByIdQueryHandler : IRequestHandler<GetTagByIdQuery, Tag>
    {
        private readonly IUnitOfWork _unitOfWork;

        public GetTagByIdQueryHandler(IUnitOfWork unitOfWork)
        {
            _unitOfWork = unitOfWork;
        }

        public async Task<Tag> Handle(GetTagByIdQuery request, CancellationToken cancellationToken)
        {
            return await _unitOfWork.Tags.GetAsync(request.Id);
        }
    }
}


// Action method
public async Task<IActionResult> Edit(int id)
{
    return View(await _mediator.Send(new GetTagByIdQuery { Id = id }));
}

How can I make sure that the given ID is valid?

Second question description

For example:

If the user request the tag with invalid tag ID:

https://localhost:44343/admin/tags/edit/80

I want to redirect the user to the 404 error page.


Solution

  • For both questions, When the tag ID is invalid, the query result will be null, so we can handle it like this:

    public async Task<IActionResult> Edit(int id)
    {
        var query = new GetTagByIdQuery { Id = id };
        var result = await _mediator.Send(query);
    
        return result is not null ? View(result) : (IActionResult)NotFound();
    }