如何在 C# api 中设置所需的参数

Posted

技术标签:

【中文标题】如何在 C# api 中设置所需的参数【英文标题】:How to make parameter required in 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();

【问题讨论】:

【参考方案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);

【讨论】:

以上是关于如何在 C# api 中设置所需的参数的主要内容,如果未能解决你的问题,请参考以下文章

无法在 Chrome DevTools 中设置所需的断点?

如何使用 aws cloudformation 模板在 aws cognito 用户池中设置所需属性?

如何在下拉框中设置所选项目

如何在 reactstrap 下拉菜单中设置所选项目?

如何在 BottomNavigationView 中设置所选项目

如何在 Select 元素中设置所选项目的背景颜色?