Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC JSON body with POST

I am new to ASP.NET MVC and learning. So far I have figured out how I can create a JSON Object and return that as a response to a request. However, I'm not able to pass a JSON body as part of a POST request like I normally did using Java.

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. Here's the code for the Action method -

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 -

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 -

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

like image 404
Ajay Kelkar Avatar asked Aug 16 '15 12:08

Ajay Kelkar


2 Answers

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

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

The default value is [HttpGet] that get parameters from url. For Post request you need to.

Edit:

And look the answer from vinayan

with jquery:

$.ajax({
  method: "POST",
  url: "Home/Search",
  data: {'a': 'yourstring'}
})
like image 189
Tchaps Avatar answered Oct 07 '22 13:10

Tchaps


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:

protected void Application_Start()
{
    // some code here

    ValueProviderFactories.Factories.Add(new JsonValueProviderFactory());
}
like image 32
Sam FarajpourGhamari Avatar answered Oct 07 '22 14:10

Sam FarajpourGhamari