how to post arbitrary json object to webapi

前端 未结 4 965
甜味超标
甜味超标 2020-12-14 01:20

How do I / is it possible to pass in a json object to a webapi controller (POST) and not have a class to map it to, but rather handle it as arbitrary content?

相关标签:
4条回答
  • 2020-12-14 01:28

    You can have your post method that takes in a HttpRequestMessage to by pass the model binding logic and you can read the content of the request directly:

        public HttpResponseMessage Post(HttpRequestMessage req)
        {
            var data = req.Content.ReadAsStringAsync().Result; // using .Result here for simplicity...
            ...
    
        }
    

    By the way, the reason why the action that takes in JObject doesn't work is because of 'ObjectId("...")' that is used as the value of "_id" in your data...

    0 讨论(0)
  • 2020-12-14 01:31

    In your input, "_id": ObjectId("5069f825cd4c1d590cddf206") is what is breaking the JSON materialization on the server. Removing ObjectId and using "_id" : "5069f825cd4c1d590cddf206" works with JObject as well as Dictionary<string, object>

    0 讨论(0)
  • 2020-12-14 01:34

    We passed json object by jquery, and parse it in dynamic object. it works fine. this is sample code:

    ajaxPost:
    
    ...
    Content-Type: application/json,
    data: {
              "name": "Jack", 
              "age": "12"
          }
    ...
    

    webapi:

    [HttpPost]
    public string DoJson2(dynamic data)
    {
        string name = data.name;
        int age = data.age;
    
        return name;
    }
    

    similary question on stackoverflow: WebAPI Multiple Put/Post parameters

    0 讨论(0)
  • 2020-12-14 01:35

    It is very easy, you just need to put the Accept Header to "application/json".

    0 讨论(0)
提交回复
热议问题