查询字符串中的C#Web API可选参数 [英] C# Web API Optional parameters in query string

查看:91
本文介绍了查询字符串中的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可选参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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