use*_*285 19 c# query-string asp.net-core
我想做这个,但我也想能够在阵列传递到查询字符串.我尝试过这样的事情:
http://www.sitename.com/route?arr[]=this&arr[]=that
http://www.sitename.com/route?arr[]=this&that
http://www.sitename.com/route?arr[0]=this&arr[1]=that
http://www.sitename.com/route?arr0=this&arr1=that
http://www.sitename.com/route?arr=this&arr=that
Run Code Online (Sandbox Code Playgroud)
我在C#代码中的路由如下所示:
[Route("route")]
[HttpGet]
public void DoSomething(string[] values)
{
// ...
}
Run Code Online (Sandbox Code Playgroud)
但在所有这些情况下,当它到达C#代码时,值始终为null.我需要什么查询字符串来传递字符串数组?
Moh*_*reh 20
定界字符串不是标准.如果你支持招摇或其他发电机,也要考虑客户.
对于那些想知道收到空列表的.net core 2.1 bug的人来说,解决方法就在这里:https://github.com/aspnet/Mvc/issues/7712#issuecomment-397003420
它需要FromQuery上的名称参数
[FromQuery(Name = "employeeNumbers")] List<string> employeeNumbers
Run Code Online (Sandbox Code Playgroud)
Ily*_*kov 17
在查询字符串中使用参数名称.如果你有一个动作:
public void DoSomething(string[] values)
Run Code Online (Sandbox Code Playgroud)
然后values
在查询字符串中使用将数组传递给服务器:
?values=this&values=that
Run Code Online (Sandbox Code Playgroud)
最后,我只是传入一个单独的分隔字符串,然后在服务器端使用 string.Split 进行分隔。不是最漂亮的解决方案,但它有效。在有人想出更好的答案之前,这就是我所得到的。我应该重申我使用的是 .NET Core,并且这些查询字符串是特定于框架的。
更新:这种方法的一个(有争议的)好处是您将值一起传递(例如 arr=value1,value2)而不是重复键(arr=value1&arr=value2)。
我发现你的问题有两个问题:
arr
而您的控制器的操作具有values
.ModelBinder
可以按预期工作。像这样:public void DoSomething([FromQuery(Name = "values")] string[] values)
Run Code Online (Sandbox Code Playgroud)
完成此操作后,一切都应该按预期进行。
我必须执行类似的操作,但是我使用了long列表来传递一些id进行搜索,而不是使用字符串。使用多选选项,将所选值发送到方法(通过get),如下所示:
[HttpGet("[action]")]
public IActionResult Search(List<long> idsSelected)
{
///do stuff here
}
Run Code Online (Sandbox Code Playgroud)
我也在Route("[controller]")
类声明之前使用。效果很好,但是项目列表在url中分为多个参数,如下所示。
http://localhost:5000/Search/idsSelected=1&idsSelected=2
Run Code Online (Sandbox Code Playgroud)
鉴于:
public ValuesController
{
public IACtionResult Get([FromUri]string[] arr)
{
Return Ok(arr.Length);
}
}
Run Code Online (Sandbox Code Playgroud)
以下请求将起作用:
GET /api/values/?arr[0]=a&arr[1]=b&arr[2]=c
Run Code Online (Sandbox Code Playgroud)
我找到了解决方案。例如,如果您有这样的查询http://www.sitename.com/route?arr[]=this&arr[]=that。您必须在操作中定义下一个代码[FromQuery(Name =“ arr []”)]。参数名称必须带有方括号“ arr []”。结果,我们可以看到:
公共无效DoSomething([FromQuery(Name =“ arr []”)]字符串[] arr)
归档时间: |
|
查看次数: |
23826 次 |
最近记录: |