当需要其他参数时,如何正确使用WebAPI/Rest [英] How do I use WebAPI/Rest correctly when other params are needed

查看:57
本文介绍了当需要其他参数时,如何正确使用WebAPI/Rest的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是WebAPI的新手,可以休息并尝试正确地做事.默认情况下,如果我要访问诸如User之类的东西,如果我想要用户5,我会调用api/user/5.这将进入我的User控制器以获取Get(int num).但是我知道我也经常需要通过其他参数.目前,我有Get(JObject data),但是该数据参数用于其他参数.无论我要发送ID还是想要所有内容的列表,我都需要其他可选参数.如何使用WebAPI正确组织方法?我误会了吗?

I am new to WebAPI and rest and am trying to do things correctly. By default if I were to access something such as User I would call api/user/5 if I wanted user 5. This would go to my User controller to Get(int num) I think. But I know I will often need other params passed as well. Currently I have Get(JObject data), but that data param is for other parameters. I will need other optional params whether I am sending an ID or wanting a list of everything. How do I go about organizing methods properly with WebAPI? Am I misunderstanding something?

要澄清:这个问题更多的是关于REST,而不是动态对象,尽管它们发挥了作用:

To clarify: This question is more about REST than dynamic objects, though they play a part:

当我需要其他参数时,如何获得单个资源与资源列表.我将这些概念视为两个独立的方法,但是当涉及到路由时,其他一些参数使它复杂化.

How do I get a single resource vs a list of resources when I need additional params. I see those concepts as two separate methods, but the additional params complicate it in my mind when routing is involved.

推荐答案

使用例如-

[Route("customers/{customerId}/orders")]
public IEnumerable<Order> GetOrdersByCustomer(int customerId) { ... }

[Route("customers/{customerId}/orders/{orderId}")]
public Order GetOrderByCustomer(int customerId, int orderId) { ... }

如果您需要返回列表,请创建一个返回列表的方法,否则返回所请求的特定项目

if you need to return a list, create a method that returns a list, otherwise return the specific item requested

这篇关于当需要其他参数时,如何正确使用WebAPI/Rest的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆