6

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?

1 Answer 1

8

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);
}
Sign up to request clarification or add additional context in comments.

1 Comment

Oh, man, thank you and i what chidrens from you)) its joke)) and can you give me some linлs with docs about WebApi besides asp.net/mvc?

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.