【发布时间】:2018-07-25 08:44:48
【问题描述】:
我正在尝试从我的 URI 的 querystring 检索 int 值,但遇到了一些问题。
我有一个如下的请求 URI
http://localhost:64813/api/MyController/GetTree?%24filter=parentId%20eq%207
我通过邮递员发送它,控制器接收它,但我无法访问parentId 的值。我做错了什么?
这是我迄今为止在控制器上尝试过的……但这些尝试都没有奏效……
1) 我试图检索一个名为 string 的过滤器,但它是 null...
[AllowAnonymous]
[HttpGet("GetTree")]
public IActionResult GetTree(string filter)
{
int q = filter.LastIndexOf(" eq ");
string r = parentId.Substring(q);
int result = Convert.ToInt32(r);
2) 我尝试使用[FromQuery] 从filter 访问parentId,但没有。始终为null 值。
[AllowAnonymous]
[HttpGet("GetTree")]
public IActionResult GetTree([FromQuery(Name = "filter")] string parentId)
{
int q = parentId.LastIndexOf(" eq ");
string r = parentId.Substring(q);
int result = Convert.ToInt32(r);
3) 就像第二次尝试一样,但我尝试获取整个查询。你可以猜到,string 是null,再次......
[AllowAnonymous]
[HttpGet("GetTree")]
public IActionResult GetNodi([FromQuery] string filter)
{
int q = filter.LastIndexOf(" eq ");
string r = filter.Substring(q);
int result = Convert.ToInt32(r);
其他值得注意的尝试:
4) 尝试 #2,但我尝试将 parentId 解析为 int 而不是 string。没什么,默认值始终为零,即使我更改了请求值。
5) 尝试使用 try #1、try #2 和 #3 将 filter 解析为对象(见下文)。字符串始终为null。
public class NodeReq
{
public string ParentId { get; set; }
}
我做错了什么?如何访问此查询字符串 parentId 值?
【问题讨论】:
-
为什么是
%24? -
您是否尝试创建类似 url 架构的 oData?
-
... 好的,要让 OData 为您自己的路由模式工作,您需要包括路由和库。它需要最少的设置。你做到了吗?
-
好的,祝你好运:我自己做过一次......这很困难,因为文档有点......简约。
-
这里还有一些关于这个主题的东西:github.com/OData/WebApi/issues/1177#issuecomment-358659774
标签: c# asp.net-core .net-core