简体   繁体   English

如何使 C# api 中所需的参数

[英]How to make parameter required in C# api

so for now it will match both of the actions by the route api/comments, I want the second one to be api/comments?blogId=1, but I don't want it to be api/comments/{blogId}.所以现在它会通过路由 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();
}

Routes are unique by looking at there themplate.通过查看那里的模板,路线是独一无二的。 Even if you're using blogId as query parameter, the two actions are using the same route template which is this api/comments .即使您使用blogId作为查询参数,这两个操作也使用相同的路由模板,即此api/comments

To do what you're trying to do is to using only have one action that will return result when you send a blogId or not.要做你想做的事情是只使用一个动作,当你发送一个blogId或不发送时,它会返回结果。

So just add one action Get and the logic should look like below:因此,只需添加一个操作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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM