【问题标题】:FromUri query string web apiFromUri 查询字符串 web api
【发布时间】:2020-03-06 03:09:15
【问题描述】:

我正在尝试使用 Web Api 从我的数据库中查询数据。问题是当我使用 Postman 发送获取请求时出现错误。我在我的程序中设置了断点,但该方法没有收到请求。

{
    "Message": "The requested resource does not support http method 'GET'."
}

我尝试查询以下字符串:

https://localhost:44384/api/advertentie/search?location=Makarska&property=null&price=null&rooms=null&beds=null&baths=null
public class QueryModel
{
    public string Location { get; set; }
    public string Property { get; set; }
    public decimal? Price { get; set; }
    public int? Rooms { get; set; }
    public int? Beds { get; set; }
    public int? Baths { get; set; }

}

[HttpGet]
[Route("api/advertentie/search{Location}/{Property}/{Price}/{Rooms}/{Beds}/{Baths}")]
public IHttpActionResult Search([FromUri] QueryModel query)
{

}

【问题讨论】:

  • 您的路线与您的网址不匹配。您的 URL 使用查询字符串,但您的路由使用斜杠。您需要选择一种方法。
  • 我想要我的查询字符串方法。我需要从我的路线中删除斜线吗?
  • 可能需要从您的路线中删除search 之后的所有内容,因为您的查询字符串信息不应该在您的路线中。
  • 嗯,对。谢谢。
  • @mason,但我不明白的是:我在Search 中有ModelState.IsValid,但它返回错误。当我查看错误时,它显示The value 'null' is not valid for Rooms." 这意味着所有的int,但我使用? 将其设为可空类型。当我为LocationProperty 输入null 时,它不会给出任何错误。你有什么想法吗?

标签: c# asp.net webapi


【解决方案1】:

正如@mason 所指出的,您使用的是两种不同的 URL 方案。如果你想使用查询参数,你应该使用[FromQuery]。然后,您可以将路线更改为简单的[Route("api/advertentie/search")]。最终结果应该是这样的

[HttpGet]
[Route("api/advertentie/search")]
public IHttpActionResult Search([FromQuery] QueryModel query)
{

}

【讨论】:

    猜你喜欢
    • 2015-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-19
    • 2020-08-26
    • 1970-01-01
    • 1970-01-01
    • 2012-08-05
    相关资源
    最近更新 更多