Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieve a value from a request with content type application/json

I have the following script that is sending data to a controller in MVC:

$.ajax({
    url: '/products/create',
    type: 'post',
    contentType: 'application/json; charset=utf-8',
    data: JSON.stringify({
        'name':'widget',
        'foo':'bar'
    })
});

My controller looks like this:

[HttpPost]
public ActionResult Create(Product product)
{
    return Json(new {success = true});
}

public class Product 
{ 
    public string name { get; set; }
}

Is there a way I can get the "foo" variable in my controller action without

  • modifying the model
  • modifying the signature of the action

If it was a regular form submission, I would have access to Request.Form["foo"], but this value is null since it was submitted via application/json.

I want to be able to access this value from an Action Filter and that is why I don't want to modify the signature/model.

like image 606
Dismissile Avatar asked May 31 '12 15:05

Dismissile


1 Answers

I wanted to do almost exactly the same today and found this question with no answer. I also solved it with similar solution as Mark.

This works very well for me in asp.net MVC 4. Could maybe help someone else reading this question even if it is an old one.

        [HttpPost]
        public ActionResult Create()
        {
            string jsonPostData;
            using (var stream = Request.InputStream)
            {
                stream.Position = 0;
                using (var reader = new System.IO.StreamReader(stream))
                {
                    jsonPostData = reader.ReadToEnd();
                }
            }
            var foo = Newtonsoft.Json.JsonConvert.DeserializeObject<IDictionary<string, object>>(jsonPostData)["foo"];

            return Json(new { success = true });
        }

The important part was to reset the position of the stream because it is already read by some MVC internal code or whatever.

like image 149
John Avatar answered Oct 09 '22 08:10

John