Post json data in body to web api

后端 未结 2 1380
星月不相逢
星月不相逢 2021-02-14 16:50

I get always null value from body why ? I have no problem with using fiddler but postman is fail.

I have a web api like that:

    [Route(\"api/account/Ge         


        
相关标签:
2条回答
  • 2021-02-14 17:15

    WebAPI is working as expected because you're telling it that you're sending this json object:

    { "username":"admin", "password":"admin" }
    

    Then you're asking it to deserialize it as a string which is impossible since it's not a valid JSON string.

    Solution 1:

    If you want to receive the actual JSON as in the value of value will be:

    value = "{ \"username\":\"admin\", \"password\":\"admin\" }"
    

    then the string you need to set the body of the request in postman to is:

    "{ \"username\":\"admin\", \"password\":\"admin\" }"
    

    Solution 2 (I'm assuming this is what you want):

    Create a C# object that matches the JSON so that WebAPI can deserialize it properly.

    First create a class that matches your JSON:

    public class Credentials
    {
        [JsonProperty("username")]
        public string Username { get; set; }
    
        [JsonProperty("password")]
        public string Password { get; set; }
    }
    

    Then in your method use this:

    [Route("api/account/GetToken/")]
    [System.Web.Http.HttpPost]
    public HttpResponseBody GetToken([FromBody] Credentials credentials)
    {
        string username = credentials.Username;
        string password = credentials.Password;
    }
    
    0 讨论(0)
  • 2021-02-14 17:23

    You are posting an object and trying to bind it to a string. Instead, create a type to represent that data:

    public class Credentials
    {
        public string Username { get; set; }
        public string Password { get; set; }
    }
    
    [Route("api/account/GetToken/")]
    [System.Web.Http.HttpPost]
    public HttpResponseBody GetToken([FromBody] Credentials value)
    {
        string result = value.Username;
    }
    
    0 讨论(0)
提交回复
热议问题