代码改变世界

【WEBAPI】常用参数传递方法总结

2013-02-25 11:25  朱峰(Peter.zhu)  阅读(713)  评论(0编辑  收藏  举报

本部分纯属代码,如有疑问,请参考之前的BLOG文章

一、C#部分

1.1 实体类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

using System.Runtime.Serialization;
using Newtonsoft.Json;

namespace TestOauth.Models
{
    //[Serializable]
    [DataContract]
    //[JsonObject(MemberSerialization.OptIn)]
    public class OAuthModels
    {
        public OAuthModels()
        {

        }

        //[DataMember]
        [JsonIgnore]
        public string ID
        {
            get;
            set;
        }

        //[JsonProperty(PropertyName = "oauth_consumer_key", NullValueHandling = NullValueHandling.Ignore)]
        [DataMember(Name = "oauth_consumer_key")]
        public string Consumer_key
        {
            get;
            set;
        }

        [JsonIgnore]
        public string Consumer_secret
        {
            get;
            set;
        }

        [JsonProperty(PropertyName = "oauth_signature_method", NullValueHandling = NullValueHandling.Ignore)]
        public string Signature_method
        {
            get;
            set;
        }

        [JsonProperty(PropertyName = "oauth_timestamp", NullValueHandling = NullValueHandling.Ignore)]
        public string Timestamp
        {
            get;
            set;
        }

        [JsonProperty(PropertyName = "oauth_nonce", NullValueHandling = NullValueHandling.Ignore)]
        public string Nonce
        {
            get;
            set;
        }

        [JsonProperty(PropertyName = "oauth_signature", NullValueHandling = NullValueHandling.Ignore)]
        public string Signature
        {
            get;
            set;
        }

        [JsonProperty(PropertyName = "oauth_token", NullValueHandling = NullValueHandling.Ignore)]
        public string Token
        {
            get;
            set;
        }

        [JsonProperty(PropertyName = "oauth_token_secret", NullValueHandling = NullValueHandling.Ignore)]
        public string Token_secret
        {
            get;
            set;
        }
    }
}

 

1.2 ACTION方法

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using TestOauth.Models;
using Newtonsoft.Json.Linq;

namespace TestOauth.Controllers
{
    public class WebAPITestController : ApiController
    {
        [HttpGet]
        public string TestGet()
        {
            return "HelloWorld";
        }

        [HttpGet]
        public OAuthModels TestGetString(string model)
        {
            OAuthModels d = Newtonsoft.Json.JsonConvert.DeserializeObject<OAuthModels>(model);

            d.Token = "requestkey";

            d.Token_secret = "requestsecret";

            return d;
        }

        [HttpPost]
        public OAuthModels TestPOSTString([FromBody]string model)
        {
            OAuthModels d = Newtonsoft.Json.JsonConvert.DeserializeObject<OAuthModels>(model);

            d.Token = "requestkey";

            d.Token_secret = "requestsecret";

            return d;
        }

        [HttpPost]
        public OAuthModels TestPOSTModel([FromBody]OAuthModels model)
        {
            model.Token = "requestkey";

            model.Token_secret = "requestsecret";

            return model;
        }

        /// <summary>
        /// didn't support this method
        /// </summary>
        /// <param name="model"></param>
        /// <param name="userToken"></param>
        /// <returns></returns>
        [HttpPost]
        public OAuthModels TestMultipleWithWrongMethod([FromBody]OAuthModels model, string userToken)
        {
            model.Token = "requestkey";

            model.Token_secret = "requestsecret";

            return model;
        }

        [HttpPost]
        public OAuthModels TestMultipleWithJObject(Newtonsoft.Json.Linq.JObject jobj)
        {
            dynamic d = jobj;

            JObject oauthModel = d.model;

            JObject oauthModel2 = d.model2;

            string token = d.userToken;

            var model = oauthModel2.ToObject<OAuthModels>();

            model.Token = "requestkey";

            model.Token_secret = "requestsecret";

            return model;
        }


        [HttpPost]
        public OAuthModels MyAction(HttpRequestMessage request)
        {
            // make explicit calls to get parameters from the request object
            int id = int.Parse(request.RequestUri.ParseQueryString().Get("id")); // need error logic!

            OAuthModels model = request.Content.ReadAsAsync<OAuthModels>().Result; // should be async!

            // Now use id and customer

            model.Token = "requestkey";

            model.Token_secret = "requestsecret";

            return model;

        }


    }
}

 

 

二、HTML部分

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>TestCase</title>
    <script src="Scripts/jquery-1.7.1.js" type="text/javascript"></script>
    <style type="text/css">
        * { margin: 0px; padding: 0px; font-size: 12px; }
    </style>    
</head>
<body>
    <div id="OutPut">
    </div>
    <h1>
        Passing single Parameters to a Web API Controller</h1>
    <div>
        <h2>
            测试 单一参数POST STRING 类型</h2>
        <input id="btnTestPostString" type="button" value="button" />
    </div>
    <div>
        <h2>
            测试 单一参数GET STRING 类型</h2>
        <input id="btnTestGetString" type="button" value="button" />
    </div>
    <div>
        <h2>
            测试 Test POST Model</h2>
        <input id="btnTestPOSTModel1" type="button" value="Using the Model Binder with plain POST values" />
        <input id="btnTestPOSTModel2" type="button" value="Using Web API JSON Formatter" />
    </div>
    <h1>
        Passing multiple Parameters to a Web API Controller</h1>
    <div>
        <h2>
            测试 多个参数 类型</h2>
        <input id="btnTestMultiple" type="button" value="Test Multiple parameters With JObject" />
    </div>
</body>
</html>

 

 

三、JS部分

<script type="text/javascript">
        jQuery(document).ready(function () {

            var formData = {
                "oauth_signature": "signature from js form",
                "oauth_timestamp": "timestamp from js form"
            };

            var model = {
                "Signature": "signature from js model",
                "Timestamp": "timestamp from js model"
            };

            $("#btnTestPostString").click(function () {

                $.ajax({
                    type: "POST",
                    url: "http://localhost:9270/api/WebAPITest/TestPOSTString",
                    data: "=" + JSON.stringify(formData),
                    dataType: 'json',
                    success: function (data, textStatus, jqXHR) {
                        $("#OutPut").html(JSON.stringify(data));
                    },
                    error: function (jqXHR, textStatus, errorThrown) {
                        $("#OutPut").html(errorThrown);
                    }
                });

            });

            $("#btnTestGetString").click(function () {

                $.ajax({
                    type: "GET",
                    url: "http://localhost:9270/api/WebAPITest/TestGetString",
                    data: "model=" + JSON.stringify(formData),
                    dataType: 'json',
                    success: function (data, textStatus, jqXHR) {
                        $("#OutPut").html(JSON.stringify(data));
                    },
                    error: function (jqXHR, textStatus, errorThrown) {
                        $("#OutPut").html(errorThrown);
                    }
                });

            });

            $("#btnTestPOSTModel1").click(function () {

                $.ajax({
                    type: "POST",
                    url: "http://localhost:9270/api/WebAPITest/TestPOSTModel",
                    data: model,
                    dataType: 'json',
                    success: function (data, textStatus, jqXHR) {
                        $("#OutPut").html(JSON.stringify(data));
                    },
                    error: function (jqXHR, textStatus, errorThrown) {
                        $("#OutPut").html(errorThrown);
                    }
                });

            });

            $("#btnTestPOSTModel2").click(function () {

                $.ajax({
                    type: "POST",
                    url: "http://localhost:9270/api/WebAPITest/TestPOSTModel",
                    //here cannot use JSON.stringify(model) -- mapping error
                    data: JSON.stringify(formData),
                    dataType: 'json',
                    contentType: "application/json",
                    success: function (data, textStatus, jqXHR) {
                        $("#OutPut").html(JSON.stringify(data));
                    },
                    error: function (jqXHR, textStatus, errorThrown) {
                        $("#OutPut").html(errorThrown);
                    }
                });

            });

            $("#btnTestMultiple").click(function () {

                $.ajax({
                    type: "POST",
                    url: "http://localhost:9270/api/WebAPITest/TestMultipleWithJObject",
                    //here cannot use JSON.stringify(model) -- mapping error
                    data: JSON.stringify({
                        model: formData,
                        userToken: "testuserToken",
                        model2: {
                            "oauth_signature": "signature from js form model2",
                            "oauth_timestamp": "timestamp from js form model2"
                        }
                    }),
                    dataType: 'json',
                    contentType: "application/json",
                    success: function (data, textStatus, jqXHR) {
                        $("#OutPut").html(JSON.stringify(data));
                    },
                    error: function (jqXHR, textStatus, errorThrown) {
                        $("#OutPut").html(errorThrown);
                    }
                });

            });

        });
    </script>

 

四、输出