Vlad Vlad -4 years ago 63
reST (reStructuredText) Question

How to read post data in API Controller - MVC4

I created API controller with the wizard in Visual Studio 2010.

It created this function:

// POST api/Default1
public HttpResponseMessage PostUserProfile(UserProfile userprofile)
{
System.Diagnostics.Debug.WriteLine("Username: " + userprofile.UserName);
if (ModelState.IsValid)
{
db.UserProfiles.Add(userprofile);
db.SaveChanges();

HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, userprofile);
response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = userprofile.UserId }));
return response;
}
else
{
return Request.CreateResponse(HttpStatusCode.BadRequest);
}
}


I am unable to add the [HttpPost] annotation since I guess MVC 4 uses older API. I also get NullPointerException for the parameter userprofile, meaning the its wrong data type. What should change to the send as parameter to my PostUserProfile() function and how?
Should it be Json object or I don't know what?

Answer Source

1- your web api action should look like.

        [HttpPost]           
        public HttpResponseMessage PostUserProfile(HttpRequestMessage request, UserProfile userprofile)
        {
             // code here
        }

2 - you must use System.Web.Http and not System.Web.MVC for HttpPost to work.

3- you need to serialize your javascript data to JSON on client side and asp.net runtime will deserialize it to UserProfile object automatically, provided that your Javascript object has same property names as the UserProfile c# object

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download