ASP.NET MVC JSON body with POST

本文关键字:with POST body JSON NET MVC ASP | 更新日期: 2023-09-27 18:08:05

我是新来的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 JSON body with POST

据我所知,您希望将整个请求体传递给没有任何绑定的字符串,以便您可以用所需的方式处理传递的字符串数据。

要达到这个目的,只需编写您自己的模型绑定器:

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();
        }      
    }
}

在你的action方法中给你的binder指定所需的参数:

public string MyAction([ModelBinder(typeof(RawBodyBinder))]string json)
{
}

但是MVC也有自己的JSON模型绑定器,如果你的数据是一个标准的JSON和在请求体与Content-Type: application/json头,你可以使用MVC的JSON模型绑定器来激活JSON模型绑定器只需添加以下行在Global.asax.cs文件:

protected void Application_Start()
{
    // some code here
    ValueProviderFactories.Factories.Add(new JsonValueProviderFactory());
}

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

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

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

编辑:

看看vinayan的答案

与jquery:

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

您发送的参数名称用于反序列化。所以在这种情况下,"a"应该是json的一部分。

public string Search(string a)

所以你必须使用

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