查询字符串中的C#Web API可选参数

编程入门 行业动态 更新时间:2024-10-23 09:37:51
本文介绍了查询字符串中的C#Web API可选参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我的控制器中有这段代码:

I have this piece of code in my controller:

[HttpGet] [Route("team={team}&model={model}&date={date}&distance={distance}")] public IHttpActionResult FindVehicle([FromUri]string team = "", [FromUri]string model = "", [FromUri]DateTime? date = null, [FromUri]double distance = 0.0) { }

查询字符串的所有参数都是可选的,这就是为什么我使用默认值.

All of the parameters of the query string can be optional, which is why I used the default values.

但是,我不确定路由应该是什么,因为现在,例如,当我不指定 model 参数时,其在端点中的值最终为"model",而不是"".

However, I am not sure what the route should be, since now, when I don't specify the model parameter for example, its value in the endpoint ends up being "model", and not "".

推荐答案

您不必在 Route 属性内定义 FromUri 元素,它们将不受约束盒子:

You don't have to define FromUri elements inside Route attribute, they will be bound out of the box:

[HttpGet] [Route("route_name")] public IHttpActionResult FindVehicle([FromUri]string team = "", [FromUri]string model = "", [FromUri]DateTime? date = null, [FromUri]double distance = 0.0) { }

如果使用的是ASP.Net Core,则应改用 [FromQuery]

If you are using, ASP.Net Core, then you should use [FromQuery] instead

更多推荐

查询字符串中的C#Web API可选参数

本文发布于:2023-11-08 14:07:19,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1569588.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:可选   字符串   参数   API   Web

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!