且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用GET方法发送JSON对象

更新时间:2022-11-28 11:03:31

您正在使用$.getJSON(url, searchCriteria)getJSON 普通对象

You are sending the query to the server using $.getJSON(url, searchCriteria) and getJSON sends the searchCriteria as a url-encoded query string because your searchCriteria would fit the definition of a plain object

在服务器端,.NET Web API的默认参数绑定将在URL中查找简单"数据类型(例如int,double,string),否则将退回到正文Content.

On the server side, the default parameter binding for .NET Web API will look in the URL for "simple" data types (e.g. int, double, string), otherwise it will fall back to the body Content.

要获得Web API模型绑定以从url中提取复杂类型,例如您的ProductSearchCriteria类,您需要在参数前面添加[FromUri]属性,如下所示:

To get Web API model binding to extract a complex type from the url, like your ProductSearchCriteria class you need to add the [FromUri] attribute in front of the parameter like this:

[HttpGet]
public IEnumerable<Products> GetProducts([FromUri] ProductSearchCriteria searchCriteria) {}

有关更多详细信息,请参见此处

See here for more detail Parameter Binding in ASP.NET Web API

我认为值得尝试保留GET语义,而不是像某些人建议的那样切换到POST,因为您的代码正在有效地执行 read 操作,只要您不修改数据或状态... GET似乎都适用.

I would argue it is worth trying to preserve the GET semantics rather than switching to POST, as some have suggested, because your code is effectively doing what looks like a read operation and as long as you're not modifying data or state... a GET seems applicable.