【问题标题】:How to make parameter required in C# api如何在 C# api 中设置所需的参数
【发布时间】:2021-06-06 16:11:44
【问题描述】:

所以现在它会匹配路由 api/cmets 的两个动作,我希望第二个是 api/cmets?blogId=1,但我不希望它是 api/cmets/{blogId }。

//Get api/comments
[HttpGet]
[Route("/")]
public async Task<IActionResult> GetAll()
{
    var comments = await _context.Comments.ToListAsync();

    if(comments != null)
        return Ok(new { status = 200, comments });
    
    return NotFound();
}

//Get api/comments?blogId=1
[HttpGet]
public async Task<IActionResult> GetCommentsBy(int blogId)
{
    var allComments = await _context.Comments.ToListAsync();          

    if (allComments != null)
    {
        var commentsByBlogId = allComments.Where(c => c.BlogId == blogId);

        return Ok(new { status = 200, comments = commentsByBlogId });
    }         

    return NotFound();
}

【问题讨论】:

    标签: c# .net asp.net-web-api2 webapi


    【解决方案1】:

    通过查看那里的模板,路线是独一无二的。即使您使用blogId 作为查询参数,这两个操作也使用相同的路由模板,即api/comments

    要做你想做的事情是只使用一个动作,当你发送blogId时返回结果。

    所以只需添加一个动作Get,逻辑应该如下所示:

    [HttpGet]
    public async Task<IActionResult> GetComments(int? blogId /* blogId i nullable so it is not required */)
    {
        // Gets the comments query but don't execute it yet. So no call to ToListAsync() here.
        var commentsQuery = _context.Comments;
    
        if  (blogId.HasValue)
        {
            // When you've a blogId set in the query then add a filter to the query.
            commentsQuery = commentsQuery.Where(c => c.BlogId == blogId);
        }
    
        var comments = await commentsQuery.ToListAsync();       
    
        // When the list is empty just send it as it is. the caller should be able to handle the case where the comments list is empty and status code is 200
        // You also don't need to set the status code in your responde body. The caller should be able to get the response status first before checking the response body.
        return Ok(comments);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-12
      • 1970-01-01
      • 2017-06-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-18
      • 2019-09-22
      相关资源
      最近更新 更多