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

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(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 NextActivityPerformers { get; set; }
        public IDictionary 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
    {
        public PerformerList() {}
    }

说明:

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

你可能感兴趣的:(Asp.net,Web技术,WebAPI)