0

I am new to web api and I can't seem to send an object from the .net project through POST.

Here is the code to send the object:

public async Task<bool> CreateUser (User user)
        {
            Uri uri = new Uri(apiUrl + "api/users");
    var jsonUser = JsonConvert.SerializeObject(user);
            HttpContent content = new StringContent(jsonUser, Encoding.UTF8, "application/json");

            var postUser = await client.PostAsync(uri, content);
            string result = await postUser.Content.ReadAsStringAsync();
            if (postUser.IsSuccessStatusCode)
            {
                return true;
            }

            return false;
        }

And here is the web API code:

[HttpPost]
    public IHttpActionResult Post([FromBody]string jsonUser)
    {
        UserDTO user = JsonConvert.DeserializeObject<UserDTO>(jsonUser);
        bool tryCreate = _userRepository.CreateUser(user);

        if (tryCreate == false)
        {
            return NotFound();
        }
        return Ok();
    }

If I try to send a POST request to my web api url, it successfully sends the json string to the action, but if I try to send POST data from my web project, the Content.ReadAsStringAsync() returns:

"{"Message":"An error has occurred.","ExceptionMessage":"Value cannot be null.\r\nParameter name: value","ExceptionType":"System.ArgumentNullException","StackTrace":" at Newtonsoft.Json.JsonConvert.DeserializeObject(String value, Type type, JsonSerializerSettings settings)\r\n at Newtonsoft.Json.JsonConvert.DeserializeObject[T](String value, JsonSerializerSettings settings)\r\n at Newtonsoft.Json.JsonConvert.DeserializeObject[T](String value)\r\n at Travue.WebAPI.Controllers.UsersController.Post(String jsonUser) in C:\\Users\\Dev01\\Documents\\projects\\travue\\Travue.WebAPI\\Controllers\\UsersController.cs:line 46\r\n at lambda_method(Closure , Object , Object[] )\r\n at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.<>c__DisplayClass6_2.<GetExecutor>b__2(Object instance, Object[] methodParameters)\r\n at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.Execute(Object instance, Object[] arguments)\r\n at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ExecuteAsync(HttpControllerContext controllerContext, IDictionary`2 arguments, CancellationToken cancellationToken)\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Web.Http.Controllers.ApiControllerActionInvoker.<InvokeActionAsyncCore>d__1.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Web.Http.Controllers.ActionFilterResult.<ExecuteAsync>d__5.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__15.MoveNext()"}"
aronccs
  • 264
  • 1
  • 10
  • 28
  • 204 No Content The server has fulfilled the request but does not need to return an entity-body, and might want to return updated metainformation. The response MAY include new or updated metainformation in the form of entity-headers, which if present SHOULD be associated with the requested variant. – Jagadeesh Govindaraj Feb 20 '19 at 01:59
  • your not returning any data in you wep api .so only it receives – Jagadeesh Govindaraj Feb 20 '19 at 02:00
  • 1
    204 is a success code. – DiplomacyNotWar Feb 20 '19 at 02:03
  • The user is not inserting in the database – aronccs Feb 20 '19 at 02:07
  • Perhaps you should ask a question about that instead? Though I recommend using the [debugger](https://stackoverflow.com/questions/25385173/what-is-a-debugger-and-how-can-it-help-me-diagnose-problems) first. – DiplomacyNotWar Feb 20 '19 at 02:08
  • 1
    I suspect that the biggest problem is this: `[FromBody]string jsonUser` - you probably just want `[FromBody]UserDTO user`. See [this question](https://stackoverflow.com/questions/40853188/frombody-string-parameter-is-giving-null/40853424). You should always debug your code before posting - I'm sure if you put a breakpoint on the `UserDTO user ...` line, you would immediately see that `jsonUser` is `null`, which allows you to write a better question, and allows us to help you. – DiplomacyNotWar Feb 20 '19 at 04:05
  • I have updated my question, please check the last line – aronccs Feb 20 '19 at 06:50
  • You're not sending a response (see `return Ok();`). How would you read it? – DiplomacyNotWar Feb 20 '19 at 07:03

0 Answers0