我在 Controller 中有一个返回对象列表的方法。 Controller 的实现并不重要。该方法称为 GetAllTestsByLocationIdAndPollTypeId
并返回“Test”对象列表。 GET 需要 4 个参数,一个 locationId
、 pollTypeId
、 itemsToLoad
和一个 search
by 的字符串。我想添加更多参数,觉得在 url 中传入 6 个对象有点多。方法签名如下所示:
[HttpGet]
public IHttpActionResult GetAllTestsByLocationIdAndPollTypeId(int locationId, int pollTypeId, int itemsToLoad = 8, string search = "")
我应该传入一个包含我当前用于参数的值的模型吗?
编辑:我不能做
[HttpPost]
因为 POST
请求没有被缓存,因此可能很昂贵,在这种情况下,会很昂贵。编辑:我使用可选参数解决了查询字符串中的过滤器,以减少传入的事物数量。
最佳答案
这完全取决于你,但是当参数增加并且有大尺寸时,头大小可能会超过,因为它是 HttpGet
,其中数据作为查询字符串参数在头中发送。
您可以尝试 HttpPost
,因为它在正文中发送数据,也使用类,如果数据超过 https,则不显示参数值:
[HttpPost]
public IHttpActionResult GetAllTestsByLocationIdAndPollTypeId([FromBody]TestLocation request)
在这里,我假设您可以使用所需参数名称的公共(public)属性创建类
TestLocation
或任何您喜欢的名称。现在您需要像
JSON
一样在 stringify
之后发送类的 {'locationId':1, 'pollTypeId':1, 'itemsToLoad':10, 'search': 'your text'}
对象并将 ajax 更改为 post。既然你已经离开了你从 ajax 调用的方式,我把它留给你更新
根据@PanagiotisKanavos 的反馈(帖子未缓存)和您提供的查询字符串不长的信息,您可以尝试添加如下路由:
config.Routes.MapHttpRoute("MyRoute", "{controller}/{locationId}/{pollTypeId}/{itemsToLoad}/{search}", new { controller = "Region", action = "GetCountries" })
或者如果路由/参数对于操作方法是唯一的,则在 Controller 级别添加属性:
[Route("GetAllTestsByLocationIdAndPollTypeId/{locationId}/{pollTypeId}/{itemsToLoad}/{search}")]
[HttpGet]
public IHttpActionResult GetAllTestsByLocationIdAndPollTypeId(int locationId, int pollTypeId, int itemsToLoad = 8, string search = "")
现在你的 api 调用可以是这样的:http://localhost/controller/1/2/10/test
或
您可以尝试路由和查询的组合。例如{LocationId}/{pollType}/Tests?itemsToLoad=N&search=X 由@KirkLarkin 建议
关于c# - 何时在 API C# 中使用模型作为 url 参数的参数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52402256/