将 MediatR 从 MVC 项目迁移到 Razor Pages。无法使用基本语法

pun*_*ter 4 c# asp.net-mvc razor mediatr asp.net-core

工作的 MVC 版本是

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

RAZOR 版本是

  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);
    }

}
Run Code Online (Sandbox Code Playgroud)

RAZOR 版本不返回 JSON.. 相反,它返回..

nvalidOperationException:不支持的处理程序方法返回类型“System.Threading.Tasks.Task 1[System.Collections.Generic.IEnumerable1[Srx.Application.StatCategories.Models.StatCategoryPreviewDto]]”。Microsoft.AspNetCore.Mvc.RazorPages.Internal.ExecutorFactory.CreateHandlerMethod(HandlerMethodDescriptor handlerDescriptor)

任何想法 ?

Ale*_*der 5

剃刀页面方法应返回实现的类型,IActionResult以便正确执行操作结果。如果您需要返回 json,您可以使用JsonResult并将操作返回类型更改为IActionResult就足够了

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