ASP.NET Web Api - post object to custom action controller

asp.net-mvc, json, rest, web-services

Solution

If you intend to send a JSON request make sure you have set the `Content-Type` request header appropriately, otherwise the server doesn't know how is the request being encoded and the `user` parameter that your Api controller action takes is null:

using (var client = new WebClient())
{
    client.Headers[HttpRequestHeader.ContentType] = "application/json";
    var user = new User() { Name = "user1", Password = "pass1" };
    var json = Newtonsoft.Json.JsonConvert.SerializeObject(user);
    var result = client.UploadString(@"http://localhost:61872/api/values/createuser", json);
}

Problem

I have next ApiController ``` public class ValuesController : ApiController { // GET /api/values public IEnumerable<string> Get() { return new string[] { "value1", "value2" }; } public User CreateUser(User user) { user.Id = 1000; return user; } } ``` with next route ``` routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{action}/{id}", defaults: new { id = RouteParameter.Optional }); ``` and i want to consume this service. I can consume first method: ``` var client = new WebClient(); var result = client.DownloadString(@"http://localhost:61872/api/values/get"); ``` but i can't consume second method. When i do next: ``` var user = new User() { Name = "user1", Password = "pass1" }; var json = Newtonsoft.Json.JsonConvert.SerializeObject(user); result = client.UploadString(@"http://localhost:61872/api/values/createuser", json); ``` i catch next exception without additional information The remote server returned an error: (500) Internal Server Error. I have a two questions: - What correct way to set custom object to service method parameter? - How can i get addition information about "magic" exception like this?

Original source