【问题标题】:How to bind FromRoute to QueryObject in .net core web api?如何在.net core web api中将FromRoute绑定到QueryObject?
【发布时间】:2021-06-11 01:43:00
【问题描述】:

我有这个查询对象:

public class GetRecipeQuery: IRequest<RecipeResponse>
{
    [BindRequired]
    [FromRoute]
    public int Id {get; set;}
}

和控制器:

[ApiController]
[Route("[controller]")]
public class RecipeController
{
    private AppDbContext _context;
    private readonly IMediator _mediator;   

    public RecipeController(AppDbContext context, IMediator mediator)
    {
        _context = context;
        _mediator = mediator;
    }
    
    [HttpGet("{Id}")]
    // http://localhost:5555/Recipe/555
    public RecipeResponse Get([FromRoute]GetRecipeQuery query)
    {
        if (query.Id == 0)
        {
            throw new ArgumentException("No Id!", nameof(query.Id));
        }
        var result = _mediator.Send(query).Result;
        return result;
    } 
}

所以我看到了这个结果:

Status: 400
"The value '{Id}' is not valid for Id."

需要帮助:如何将 Id 从路由绑定到 GetRecipeQuery.Id ? 否则我需要在每个控制器方法中手动构造查询对象。

【问题讨论】:

  • 您好@nvff,欢迎来到 Stackoverflow。我认为您需要指定类型[HttpGet("{Id:int}")]?
  • 我测试了你的代码,它工作正常,但是RecipeResponse 是什么?
  • @Karney,RecipeResponse 是返回数据类。 {id,错误}

标签: c# asp.net-core asp.net-web-api .net-core


【解决方案1】:

您似乎有点混淆了路由参数和查询参数。如果你想使用 URL 参数,你在控制器中的端点应该是一个值类型:

[FromRoute]int id

那么你调用的 URL 大概是这样的:

http://localhost:8080/foo/10

如果你想使用查询参数,你的控制器端点参数应该是这样的:

[FromQuery]Foo query

Foo 看起来像这样:

public class Foo
{
    public int Id {get; set;}
}

还有你需要拨打的地址:

http://localhost:8080/foo?id=10

【讨论】:

  • 谢谢。是的,我们可以使用 [FromQuery],这很简单。但我想从路由绑定。而且,事实证明,有一个解决方案
【解决方案2】:

@tontonsevilla,回答了我的问题。谢谢。

[HttpGet("{Id:int}")] 返回 404 错误,但 [HttpGet("{id:int}")] 工作正常! Id 参数需要小写和类型。

完整的解决方案。

1)。添加查询类

public class GetRecipeQuery : IRequest<RecipeResponse>
{
    [FromRoute]
    public int Id { get; set; }
}

2)。在Controller中使用这个查询类并添加[HttpGet("{id:int}")]

 [HttpGet("{id:int}")]
 public RecipeResponse Get(GetRecipeQuery query)
 {
    // your code
 }

我需要它,因为我开始使用Mediatr

【讨论】:

    猜你喜欢
    • 2020-01-26
    • 2017-12-18
    • 2021-06-30
    • 2012-09-26
    • 2021-02-22
    • 1970-01-01
    • 2020-12-04
    • 2021-12-25
    • 2021-05-22
    相关资源
    最近更新 更多