gpt4 book ai didi

c# - 带有 POST 的 ASP.NET MVC JSON 正文

转载 作者:太空狗 更新时间:2023-10-30 00:18:43 24 4
gpt4 key购买 nike

我是 ASP.NET MVC 和学习的新手。到目前为止,我已经弄清楚如何创建一个 JSON 对象并将其作为对请求的响应返回。但是,我无法像通常使用 Java 那样将 JSON 正文作为 POST 请求的一部分传递。

这是我在那里做的代码-

@Path("/storeMovement")
@POST
@Consumes("application/json")
@Produces("application/json")
public String storeTrace(String json) {
JSONObject response = new JSONObject();
JSONParser parser = new JSONParser();
String ret = "";

try {
Object obj = parser.parse(json);
JSONObject jsonObj = (JSONObject) obj;

RecordMovement re = new RecordMovement((double) jsonObj.get("longitude"), (double) jsonObj.get("latitude"), (long) jsonObj.get("IMSI"));
ret = re.Store();

// Clear object
re = null;
System.gc();

response.put("status", ret);
} catch (Exception e) {
response.put("status", "fail " + e.toString());
}
return response.toJSONString();
}

我在 ASP.NET Action 方法中尝试了相同的操作,但在调试时看到 string 参数 a 中的值为 null。这是 Action 方法的代码 -

public string Search(string a)
{
JObject x = new JObject();

x.Add("Name", a);

return x.ToString();
}

当我像这样使用 Object(例如 - Book)时它工作正常 -

public string Search(Book a)
{
JObject x = new JObject();

x.Add("Name", a.Name);

return x.ToString();
}

在那种情况下,这本书的名字会像我预期的那样被反序列化。 Book 类的类定义 -

public class Book
{
public int ID { get; set; }
public string Name { get; set; }
}

有人可以告诉我做错了什么吗?有没有办法接受一个字符串然后然后反序列化?我希望能够接收 JSON 而不必使用对象

最佳答案

asp.net mvc中post一个数据的第一件事就是用这个属性装饰方法[Httpost]这意味着传递一个字符串应该看起来像

[HttpPost]
public string Search(string a){
// your code
}

默认值为[HttpGet],从url获取参数。对于 Post 请求,您需要。

编辑:

并查看来自vinayan 的答案

使用jquery:

$.ajax({
method: "POST",
url: "Home/Search",
data: {'a': 'yourstring'}
})

关于c# - 带有 POST 的 ASP.NET MVC JSON 正文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32034938/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com