json - 将 Json 对象参数发送到 .net Core 中的 Web Api Controller

标签 json ajax string asp.net-web-api asp.net-core

这是 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; }
}

enter image description here

最佳答案

你的代码有很多问题,也许先查阅一些初学者教程?

首先,你要看你发送的对象,很明显!

您正在发送

{
    "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/

相关文章:

java - 再次将 bytes[].toString() 转换为 byte[]

c# - 将字符串解析为 int,XSL 样式表内的 C#

python - 使用 Split 方法或 Regex 来分隔字符串

javascript - 使用 Javascript 解析 JSON 对象是行不通的

json - 使用 React hook 获取数据在嵌套 obj 属性上返回未定义

mysql - 如何使用 Servlet 和 AJAX 下载 MySQL 的 BLOB?

javascript - Ajax/iFrame/FileSystemObject 上传

json - 密码查询、格式/组返回值

javascript - JSON 在 FireFox 和 Safari (Windows Vista) 上返回空响应

javascript - 处理ajax响应异常