【问题标题】:Parsing string from a URI querystring always returns null value从 URI 查询字符串解析字符串总是返回空值
【发布时间】: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) 就像第二次尝试一样,但我尝试获取整个查询。你可以猜到,stringnull,再次......

    [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


【解决方案1】:

你的网址有误,应该是:

http://localhost:64813/api/MyController/GetTree?filter=parentId%20eq%207

除非您使用的是OData,但似乎并非如此。

如果您使用的是 OData,则无需转义字符,它应该可以使用此 URL:

http://localhost:64813/api/MyController/GetTree?$filter=parentId eq 7

如果你需要在你的 .net 核心项目中设置 OData,我建议你遵循这个包:

更新


由于您的角度设置需要像 url 架构这样的 OData,并且 我无法控制它如何构造请求查询;您的控制器需要与协议兼容。可以在此处找到有关此主题的更多信息:

https://www.nuget.org/packages/Microsoft.OData.Core/

https://github.com/OData/odata.net

OData Support in ASP.net core

更新:


应该是这个包:

https://www.nuget.org/packages/Microsoft.AspNetCore.OData/7.0.0

【讨论】:

    【解决方案2】:

    查询字符串键名应与参数名称filter 匹配,在URL 中其%24filter 您需要删除%24

    您的网址应如下所示

    http://localhost:64813/api/MyController/GetTree?filter=parentId%20eq%207
    

    【讨论】:

      猜你喜欢
      • 2020-07-10
      • 2016-12-16
      • 2019-07-25
      • 2013-09-14
      • 2016-07-21
      • 1970-01-01
      • 1970-01-01
      • 2013-04-01
      • 1970-01-01
      相关资源
      最近更新 更多