这是 Google API - Javascript 代码
var output = new Object();
output.PlaceID = place.place_id;
output.Longitude = place.geometry.location.lng();
output.Latitude = place.geometry.location.lat();
$.ajax({
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
url: 'api/StorePlaces/Get',
type: 'POST',
data: { "value":output },
success: function (result) {
// Do something with the result
}
});
Controller 如何接收
// GET api/values/5
[HttpPost("{PlaceDetails}")]
public string Get(PlaceDetails value)
{
return "value";
}
在这种情况下,我得到空值
我无法发送字符串,如果我可以发送对象就更好了。
这个可以作为接收对象
public class PlaceDetails
{
public string PlaceID { get; set; }
public string Longitude { get; set; }
public string Latitude { get; set; }
}
最佳答案
你的代码有很多问题,也许先查阅一些初学者教程?
首先,你要看你发送的对象,很明显!
您正在发送
{
"value" : {
"PlaceID" : "",
"Longitude " : "",
"Latitude " : ""
}
}
预期答案在哪里
{
"PlaceID" : "",
"Longitude " : "",
"Latitude " : ""
}
所以你必须在 JavaScript 中使用它:
$.ajax({
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
url: 'api/StorePlaces/Get',
type: 'POST',
// do not wrap it in object with value property here!!!!
data: JSON.stringify(output),
success: function (result) {
// Do something with the result
}
});
其次,您的 Controller 操作(当它是一个 post 请求时为什么叫 Get
?)... [HttPost("{PlaceDetails}")]
属性完全错误。
这需要在 route 有一个 PlaceDetails
参数。你不是这样的人!只需将其删除。此外,缺少 [FromBody]
属性来告诉它从 http 请求正文中反序列化模型
[HttpPost]
public string Get([FromBody]PlaceDetails value)
{
return "value";
}
关于json - 将 Json 对象参数发送到 .net Core 中的 Web Api Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41440586/