Copied to clipboard

Flag this post as spam?

This post will be reported to the moderators as potential spam to be looked at


  • Lars Rasmussen 5 posts 45 karma points
    Jul 13, 2019 @ 12:34
    Lars Rasmussen
    0

    [FromBody] return allways Null in Umbraco API controller

    When I upload a string (json) to the API I allways get Null.

    Client:

                WebClient Client = new WebClient();
                Client.Encoding = System.Text.Encoding.UTF8;
                Client.Headers[HttpRequestHeader.ContentType] = "application/json; charset=UTF-8";
                Client.Headers[HttpRequestHeader.Accept] = "application/json";
    
                var mLink = "http://localhost:60760/Umbraco/Api/WebApi/CreateUser";
    
                dynamic json = new JObject();
                json.FirstName = "Lars";
                json.LastName = "Rasmussen";
    
                string mBack = Client.UploadString(mLink, "POST", json.ToString());
    

    API:

    public class WebApiController : UmbracoApiController
    {
        // ~/Umbraco/Api/WebApi/CreateUser/
        public IEnumerable<WebApiCreateUser> CreateUser([FromBody] string JsonData)
        {
           // JsonData is allways NULL why? Have do I get the json string?
    
            List<WebApiCreateUser> ls = new List<WebApiCreateUser>();
            ls.Add(new WebApiCreateUser() { Message = "Succes" });          
            return ls;
         }  }
    

    Thanks for any help :-)

  • Tor Langlo 191 posts 554 karma points
    Jul 13, 2019 @ 17:10
    Tor Langlo
    0

    I'm not sure, but maybe the [FromBody] parameter needs to be a complex type compatible with the json passed from the client? I think ASP.NET Web Api will try to convert the json for you before your CreateUser method is called.

    https://docs.microsoft.com/en-us/aspnet/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api

    So maybe create a private User class with FirstName and LastName properties and use that class as the type of the parameter.

    Otherwise, look at the client side, and what the json string looks like after you've done the JObject.ToString() and see if there are any surprises there.

    -Tor

  • Bjarne Fyrstenborg 1284 posts 4018 karma points MVP 8x c-trib
    Jul 13, 2019 @ 18:01
    Bjarne Fyrstenborg
    100

    Hi Lars

    Does it work if you either define the parameter as dynamic as in this example https://stackoverflow.com/a/23135783/1693918 or prefix the posted value with = as in these examples? https://stackoverflow.com/a/11666985/1693918 https://stackoverflow.com/a/23135629/1693918

    You could also try creating a class with properties matching the json data:

    public IEnumerable<WebApiCreateUser> CreateUser([FromBody] User user) {
    
    }
    

    /Bjarne

Please Sign in or register to post replies

Write your reply to:

Draft