WebApi 的 HttpGet 和 HttpPost 传递多个参数对象的Json和Dynamic方法

本文详细介绍了如何通过将JSON字符串附加到WebAPI控制器的查询字符串内容中,并在服务器端解析JSON对象来解决参数传递问题。包括GET和POST请求的实现方式,以及如何处理复杂对象和简单对象的解析。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Some programmers are tring to get or post multiple parameters on a WebApi controller, then they will find it not easy to solve it clearly, actually, there is a simple and pragmatical solution if we use json and dynamic object.

1.HttpGet

We can append json string in the query string content, and parsed the json object in server side.

var data = { 
     UserID: "10", 
     UserName: "Long", 
     AppInstanceID: "100", 
     ProcessGUID: "BF1CC2EB-D9BD-45FD-BF87-939DD8FF9071" 
};  
var request = JSON.stringify(data);  
request = encodeURIComponent(request); 

//call ajax get method 
ajaxGet:
 ...
 url: "/ProductWebApi/api/Workflow/StartProcess?data=", 
 data: request,
 ...


[HttpGet]  
public ResponseResult StartProcess()  
{  
    dynamic queryJson = ParseHttpGetJson(Request.RequestUri.Query);  
    int appInstanceID = int.Parse(queryJson.AppInstanceID.Value);  
    Guid processGUID = Guid.Parse(queryJson.ProcessGUID.Value);  
    int userID = int.Parse(queryJson.UserID.Value);  
    string userName = queryJson.UserName.Value;  
    ...
} 

private dynamic ParseHttpGetJson(string query)  
{  
    if (!string.IsNullOrEmpty(query))  
    {  
        try  
        {  
            var json = query.Substring(7, query.Length - 7);  // the number 7 is for data=
            json = System.Web.HttpUtility.UrlDecode(json);  
            dynamic queryJson = JsonConvert.DeserializeObject<dynamic>(json);  

            return queryJson;  
        }  
        catch (System.Exception e)  
        {  
            throw new ApplicationException("wrong json format in the query string!", e);  
        }  
    }  
    else  
    {  
        return null;  
    }  
}  

2.HttpPost

2.1 Simple Object

We passed json object with ajax, and parse it with dynamic object in server side. it works fine. This is sample code:

ajaxPost:

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


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

    return name;
}

2.2 Complex Object

The complex object means that we can package list and dictionary object, and parse them with dynamic object in server side. We call this composite pattern.

var jsonData = {
   "AppName":"SamplePrice",
   "AppInstanceID":"100",
   "ProcessGUID":"072af8c3-482a-4b1c‌​-890b-685ce2fcc75d",
   "UserID":"20",
   "UserName":"Jack",
   "NextActivityPerformers":{
        "39‌​c71004-d822-4c15-9ff2-94ca1068d745":
         [{
            "UserID":10,
            "UserName":"Smith"
         }]
   }
 }

//call ajax post method
ajaxPost:
...
Content-Type: application/json,
data: jsonData
...

[HttpPost]
public string ParseJsonComplex(dynamic data)
{
   //compsite object type:
   var c = JsonConvert.DeserializeObject<YourObjectTypeHere>(data.ToString()); 

   //list or dictionary object type 
   var c1 = JsonConvert.DeserializeObject< ComplexObject1 >(data.c1.ToString());

   var c2 = JsonConvert.DeserializeObject< ComplexObject2 >(data.c2.ToString());

   ...
}
    // object type in serverside 
    public class WfAppRunner
    {
        public string AppName { get; set; }
        public int AppInstanceID { get; set; }
        public string AppInstanceCode { get; set; }
        public Guid ProcessGUID { get; set; }
        public string FlowStatus { get; set; }
        public int UserID { get; set; }
        public string UserName { get; set; }
        public IDictionary<Guid, PerformerList> NextActivityPerformers { get; set; }
        public IDictionary<string, string> Conditions { get; set; }
        public string Other { get; set; }
    }


    public class Performer
    {
        public int UserID { get; set; }
        public string UserName { get; set; }
    }


    public class PerformerList : List<Performer>
    {
        public PerformerList() {}
    }

说明:

我在stackoverflow 上发布的文章,是我的原创文章:
http://stackoverflow.com/questions/23123732/webapi-httpget-and-httppost-parameterized-with-json-and-dynamic-object

### 回答1: 当我们需要传递两个对象时,可以使用一个 `POST` 请求来发送这些对象。具体步骤如下: 1. 创建一个包含两个对象的字典 ```python data = { 'object1': object1, 'object2': object2 } ``` 2. 使用 `requests` 库发送 `POST` 请求 ```python import requests response = requests.post(url, json=data) ``` 3. 在服务器端接收并解析数据 ```python from flask import Flask, request app = Flask(__name__) @app.route('/endpoint', methods=['POST']) def endpoint(): data = request.get_json() object1 = data['object1'] object2 = data['object2'] # do something with object1 and object2 return 'success' ``` 在服务器端,我们可以使用 `request.get_json()` 方法获取发送过来的 JSON 数据,然后从中提取出我们需要的对象。注意,我们需要在 Flask 应用中设置 `methods=['POST']`,以确保只有 `POST` 请求能够访问该端点。 ### 回答2: 在计算机编程中,post 方法常用于通过 HTTP 协议向服务器发送数据。而在使用 post 方法时,传递数据可以选择使用两个对象。 第一个对象是 URL 对象,用于指定服务器的地址路径。这个对象包含了服务器的域名或 IP 地址,以及要访问的路径。通过 URL 对象,我们可以将 post 方法发送的数据发送给正确的服务器。 第二个对象是 data 对象,用于传递需要发送给服务器的数据。这个对象可以是字典、列表等数据类型,也可以是已经序列化的 JSON 格式的字符串。通过 data 对象,我们可以明确告诉服务器需要传递的数据,并将其正确地封装起来。 需要注意的是,data 对象的格式需要与服务器端的接口要求相匹配。如果服务器端要求传递的数据是 JSON 格式,那么我们就需要将待发送的数据转化为 JSON 字符串,并设置正确的 Content-Type 为 application/json。如果服务器端要求传递的数据是表单格式,那么我们需要将待发送的数据进行表单编码,并设置正确的 Content-Type 为 application/x-www-form-urlencoded。 通过这两个对象的配合,我们可以在 post 方法传递数据给服务器。服务器收到这些数据后,就可以解析并处理进行相应的操作。无论是传递用户信息、上传文件还是进行其他操作,post 的使用两个对象传递的方式都是常见且有效的。 ### 回答3: 在编程中,post 是一种常用的方法,用于发送数据到服务器端。与 get 方法不同,post 方法使用两个对象进行数据传递,分别是发送请求的对象接收请求的对象。 首先,发送请求的对象是客户端或者前端,它通过 post 方法将数据发送给服务器端。发送请求的对象将数据封装成一个请求报文,包含请求的URL地址、请求头请求体。在请求体中,可以携带需要传递的数据,如表单数据、JSON 数据等。发送请求的对象将请求报文发送给服务器端,以传递数据。 其次,接收请求的对象是服务器端或者后端。服务器端接收到请求后,通过 post 方法从请求体中解析出传递的数据。接收请求的对象通常是一个服务器资源,它根据请求的路径请求的方式来处理请求,并将响应返回给发送请求的对象。 通过 post 方法传递数据的好处是可以发送较大量的数据,并且数据不会暴露在 URL 中,更加安全。客户端与服务器端之间的数据传输,通过 post 方法,可以实现双向通信,使得网页与服务器之间的交互更加灵活。 综上所述,post 方法使用两个对象进行数据传递,发送请求的对象将数据封装成请求报文发送给接收请求的对象。这种方式使得客户端与服务器端之间可以传递大量的数据,实现双向通信,并且保证数据的安全性。
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值