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:
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With