Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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:

  1. What correct way to set custom object to service method parameter?
  2. How can i get addition information about "magic" exception like this?
like image 518
slavsergey Avatar asked May 24 '12 10:05

slavsergey


1 Answers

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);
}
like image 133
Darin Dimitrov Avatar answered Sep 18 '22 14:09

Darin Dimitrov