[英]ASP.NET MVC JSON body with POST
I am new to ASP.NET MVC
and learning. 我是
ASP.NET MVC
和学习的新手。 So far I have figured out how I can create a JSON
Object and return that as a response to a request. 到目前为止,我已经弄清楚如何创建一个
JSON
对象并将其作为对请求的响应返回。 However, I'm not able to pass a JSON
body as part of a POST
request like I normally did using Java
. 但是,我无法像通常使用
Java
那样传递JSON
正文作为POST
请求的一部分。
Here is the code how I did this there - 这是我在那里做到这一点的代码 -
@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();
}
I tried the same in the ASP.NET Action method but the value in the string
parameter a
is null
as seen while debugging. 我在ASP.NET Action方法中尝试了相同的操作,但是在调试时看到
string
参数a
值为null
。 Here's the code for the Action method - 这是Action方法的代码 -
public string Search(string a)
{
JObject x = new JObject();
x.Add("Name", a);
return x.ToString();
}
It works fine when I use an Object
(for example - Book) like so - 当我使用
Object
(例如 - Book)时,它工作正常 -
public string Search(Book a)
{
JObject x = new JObject();
x.Add("Name", a.Name);
return x.ToString();
}
In that case, the book's name gets de-serialized just fine as I would expect. 在这种情况下,这本书的名称会像我期望的那样被反序列化。 The class definition for the
Book
class - Book
类的类定义 -
public class Book
{
public int ID { get; set; }
public string Name { get; set; }
}
Can somebody please advise what I'm doing wrong? 有人可以告诉我我做错了什么吗? Is there no way to take in a string and then de-serialize?
有没有办法接受一个字符串, 然后反序列化? I'd like to be able to take in
JSON
without having to use an Object 我希望能够在不使用Object的情况下接收
JSON
As for as understand you want pass entire of request body to a string without any binding so you could handle passed string data with your desired way. 至于理解你想要将整个请求体传递给没有任何绑定的字符串,这样你就可以用你想要的方式处理传递的字符串数据。
To aim this purpose simply write your own model binder: 为此目的,只需编写自己的模型绑定器:
public class RawBodyBinder : IModelBinder
{
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
if(typeof(string)!=bindingContext.ModelType)
return null;
using (var s = new StreamReader(controllerContext.HttpContext.Request.InputStream))
{
s.BaseStream.Position = 0;
return s.ReadToEnd();
}
}
}
And in you action method assign your binder to desired parameter: 在您的操作方法中,将您的活页夹分配给所需的参数:
public string MyAction([ModelBinder(typeof(RawBodyBinder))]string json)
{
}
But MVC has own JSON model binder as well if your data is a standard JSON and in request body with Content-Type: application/json
header you could use MVC's JSON model binder to activate JSON model binder simply add following line in Global.asax.cs
file: 但是,如果您的数据是标准JSON,MVC也有自己的JSON模型绑定器,而在
Content-Type: application/json
标头的请求主体中,您可以使用MVC的JSON模型绑定器来激活JSON模型绑定器,只需在Global.asax.cs
添加以下行Global.asax.cs
文件:
protected void Application_Start()
{
// some code here
ValueProviderFactories.Factories.Add(new JsonValueProviderFactory());
}
The first thing in asp.net mvc to post a data is to decorate the method with this attribute [Httpost] it's mean passing a string should look like 在asp.net mvc中发布数据的第一件事是用这个属性装饰方法[Httpost]它的意思是传递一个字符串应该看起来像
[HttpPost]
public string Search(string a){
// your code
}
The default value is [HttpGet] that get parameters from url. 默认值是[HttpGet],它从url获取参数。 For Post request you need to.
对于Post请求,您需要。
Edit: 编辑:
And look the answer from vinayan 看看vinayan的答案
with jquery: 用jquery:
$.ajax({
method: "POST",
url: "Home/Search",
data: {'a': 'yourstring'}
})
The name of the parameter you send is used for the de-serialization. 您发送的参数的名称用于反序列化。 So in in this case, "a" should be part of json.
所以在这种情况下,“a”应该是json的一部分。
public string Search(string a)
so you will have to use, 所以你必须使用,
$.ajax({
method: "POST",
url: "Home/Search",
data: {'a': 'yourstring'}
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.