Search code examples
c#asp.net-mvcasp.net-corerazormediatr

Moving MediatR from a MVC project to Razor Pages. Cannot get basic syntax to work


The working MVC version is

 public class StatCategoriesController : BaseController
{
    [HttpGet]
    public async Task<ActionResult<IEnumerable<StatCategoryPreviewDto>>> GetStatCategoryPreview([FromQuery] GetStatCategoryPreviewQuery query)
    {
        return Ok(await Mediator.Send(query));
    }    
}

The RAZOR version is

  public class CategoriesModel : PageModel
{
    private IMediator _mediator;

    protected IMediator Mediator =>
        _mediator ?? (_mediator = HttpContext.RequestServices.GetService<IMediator>());

    public async Task<IEnumerable<StatCategoryPreviewDto>> OnGet([FromQuery] GetStatCategoryPreviewQuery query)
    {
        return await Mediator.Send(query);
    }

}

And the RAZOR verion doesn't return the JSON.. instead it returns..

nvalidOperationException: Unsupported handler method return type 'System.Threading.Tasks.Task1[System.Collections.Generic.IEnumerable1[Srx.Application.StatCategories.Models.StatCategoryPreviewDto]]'. Microsoft.AspNetCore.Mvc.RazorPages.Internal.ExecutorFactory.CreateHandlerMethod(HandlerMethodDescriptor handlerDescriptor)

Any idea ?


Solution

  • A razor page method should return type that implements IActionResult in order to properly execute action result. If you need to return json you can use JsonResult and changing action return type to IActionResult will be enough

    public async Task<IActionResult> OnGet([FromQuery] GetStatCategoryPreviewQuery query)
    {
        var result = await Mediator.Send(query);
        return new JsonResult(result);
    }