如何在 C# 中使参数成为必需的 api

How to make parameter required in C# api

所以现在它将匹配路线 api/comments 的两个动作,我希望第二个是 api/comments?blogId=1,但我不希望它是api/comments/{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();
}

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

做你想做的事情就是只使用一个动作,当你发送 blogId 或不发送 blogId 时都会 return 结果。

所以只要添加一个动作 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);
}