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



所以现在它将通过路由api/注释匹配这两个操作,我希望第二个是api/注释?blogId=1,但我不希望它是api/注释/{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时返回结果。

因此,只需添加一个操作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);
}

最新更新