3

I am using ASP.NET MVC3 controller to receive multi-part form post from WP7 app. The format of the post is something as follows:

    {User Agent stuff}
    Content-Type: multipart/form-data; boundary=8cdb3c15d07d36a

    --8cdb3c15d07d36a
    Content-Disposition: form-data; name="user"
    Content-Type: application/json

    {"UserName":"ashish","Password":"ashish"}

    --8cdb3c15d07d36a--

And my controller looks like:

    public class User
    {
        public string UserName { get; set;}
        public string Password { get; set; }
    }

    [HttpPost]
    public JsonResult CreateFeed(User user)
    {
    }

What I am seeing is that User is not bound to json and user object is always null. I tried making user string and manually bound it to User class using DataContractJsonSerializer and it does create and assign an object but I am baffled as to why it does not work.

I tried using non-multi-form post and found it works with the same json. Any help would be appreciated.

I saw these posts: ASP.NET MVC. How to create Action method that accepts and multipart/form-data and HTTP spec http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4.2 while coming up with my code.

3
  • untested, off-the-cuff answer: change name="feedItem" to name="user" ? Commented Apr 13, 2012 at 16:28
  • Actually I had it as user before. Still no luck :( Commented Apr 15, 2012 at 3:55
  • Don't you need a top-level "user" element? You do with DataContractJsonSerializer generally, but not sure what's happening here. What I mean is { "user" : { "UserName" ... } } Commented Apr 26, 2012 at 20:03

1 Answer 1

1

The answer you're looking for is here

You have to read it in as a string and parse that internally. So your action would look like this:

[HttpPost]
public JsonResult CreateFeed(string jsonResponse)
{
    JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();
    User user = jsonSerializer.Deserialize<User>(jsonResponse);
}

Or if you don't have nice helpful Content-Disposition with names to associate with the controller action methods you can do something like the below:

[HttpPost]
public JsonResult CreateFeed()
{
    StreamReader reader = new StreamReader(Request.InputStream);
    string jsonResponse = reader.ReadToEnd();

    JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();
    User user = jsonSerializer.Deserialize<User>(jsonResponse);
}

This approach is further outlined here

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.