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

I have the following 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 the following route

  routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{action}/{id}", defaults: new { id = RouteParameter.Optional }); 

and I want to use this service. I can use the first method:

  var client = new WebClient(); var result = client.DownloadString(@"http://localhost:61872/api/values/get"); 

but I can not use the second method. When I do the following:

  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 will catch the following exception without further information

The remote server responded with an error: (500) Internal server error.

I have two questions:

  • What is the correct way to set a custom object parameter to a service method?
  • How can I get more information about a magic exception like this?
+6
source share
1 answer

If you intend to send a JSON request, make sure that you have correctly configured the Content-Type request header, otherwise the server does not know how the request is encoded, and the user parameter that accepts your Api controller action. zero:

 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); } 
+8
source

Source: https://habr.com/ru/post/916548/


All Articles