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.

Community
  • 1
  • 1
Ashish Kaila
  • 447
  • 7
  • 11

1 Answers1

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

Community
  • 1
  • 1
Eoin
  • 123
  • 7