简体   繁体   中英

send neatly formatted json data to asp.net web api instead of default [FromBody] behavior

I am trying to figure out a way to send a Json formatted data to a web api controller in a neat(more natural) way.

let me explain. Suppose I have this controller:

[HttpPost]
public class StudentController : ApiController
{

    public void PostSomething([FromBody] string name, [FromBody] Student s) 
    {
        //do something
    }
}

The json data that I WANT to post is something like this (as it is correctly formatted):

{
    "name" : "John",
    "student" : {
        "id" : "1",
        "age" : "22"
    }
}

But what I SHOULD send for the web api to parameter bind the objects should be like this:

{
    "John",
    {
        "id" : "1",
        "age" : "22"
    }
}

The problem is that if I use my desired json format, both name and student objects will be null in the PostSomething method of the controller.

How can I send a json request with a format similar to the first example to my web api controller?

In order to consume the desired JSON structure you can change the method signature of the PostSomething and introduce a class that represents the sent data. Eg

public class StudentTransferObject {
    public string Name {get; set;}
    public Student Student {get; set;}
}

With the Controller:

[HttpPost]
public class StudentController : ApiController
{    
    public void PostSomething([FromBody] StudentTransferObject studentInformation) 
    {
        //do something
    }
}
  1. Read text from response body and parse the objects yourself:

    [HttpPost] public async Task<string> PostSomething() { string result = await Request.Content.ReadAsStringAsync(); //parse here how you want return result; }

  2. Dynamic serialization with custom binding or JToken .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM