webApi——傳參詳解

前臺html 效果
這裏寫圖片描述

html

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
    <script src="../Scripts/jquery-1.10.2.min.js"></script>
    <script type="text/javascript">

        $(function () {

            //普通get
            $("#SimpleGet").click(function () {
                $.ajax({
                    type: "get",
                    url: "/api/Test/SimpleGet",
                    data: { id: 1, name: "tangli", bir: "1988-09-11" },
                    success: function (data, status) {

                    }
                });
            });

            //get傳遞對象

            $("#GetSendModel").click(function () {
                var postdata = { ID: "2", Name: "Jim", CreateTime: "1988-09-11" };
                $.ajax({
                    type: "get",
                    url: "/api/Test/GetSendModel",
                    data: postdata,
                    success: function (data, status) { }
                });
            });

            //如果你不想使用[FromUri]這些在參數裏面加特性的這種“怪異”寫法,也可以採用先序列化,再在後臺反序列的方式


            $("#GetSendModel2").click(function () {
                $.ajax({
                    type: "get",
                    url: "/api/Test/GetSendModel",
                    contentType: "application/json",
                    data: { strQuery: JSON.stringify({ ID: "3", Name: "zd", CreateTime: "1988-09-11" }) },
                    success: function (data, status) {

                    }
                });
            });


            $("#PostOneData").click(function () {
                $.ajax({
                    type: "post",
                    url: "/api/Test/PostOneData",
                    data: { "": "Jim"},
                    success: function (data, status) { }
                });
            });

            $("#PostManyData").click(function () {
                var str = JSON.stringify({ Name: "jiaguanyao", Des: "備註", CreateTime: "1988-09-11" });
                $.ajax({
                    type: "post",
                    url: "/api/Test/PostManyData",
                    data: { "": str },
                    success: function (data, status) { }
                });
            });

            $("#PostManyData2").click(function () {
                $.ajax({
                    type: "post",
                    url: "/api/Test/PostManyData2",
                    data: { "name": "maozhedong", "des": "weida" },
                    success: function (data, status) { }
                });
            });


            //有一點需要注意的是這裏在ajax的請求裏面需要加上參數類型爲Json,即 contentType: 'application/json', 這個屬性。
            $("#PostModel").click(function () {
                $.ajax({
                    type: "post",
                    url: "/api/Test/PostModel",
                    contentType: 'application/json',
                    data: JSON.stringify({ Name: "jianbin", Des: "備註", CreateTime: "1988-09-11" }),
                    success: function (data, status) { }
                });
            });

        });
    </script>
</head>
<body>
    <h1>Get</h1>
    <input type="button" id="SimpleGet" value="簡單Get" />

    <input type="button" id="GetSendModel" value="Get方式傳對象" />

    <input type="button" id="GetSendModel2" value="Get方式傳對象(先序列化)" />

    <h1>Post</h1>

    <input type="button" id="PostOneData" value="Post一個數據" />
    <input type="button" id="PostManyData" value="Post多個數據【不推薦】" />
    <input type="button" id="PostManyData2" value="Post多個數據(後臺方法2)" />
    <input type="button" id="PostModel" value="Post對象" />
</body>
</html>

WebApiConfig

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

namespace Hzb.File
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API 配置和服務

            // Web API 路由
            config.MapHttpAttributeRoutes();

            //找到了與該請求匹配的多個操作: 類型 Hzb.File.Controllers.TestController 的 SaveData 類型 Hzb.File.Controllers.TestController 的 PostModel
            //注意 要加在默認路由的上面
            config.Routes.MapHttpRoute(
                 name: "DefaultApinew",
                 routeTemplate: "api/{controller}/{action}/{id}",
                 defaults: new { id = RouteParameter.Optional }
            );


            config.Routes.MapHttpRoute(
               name: "DefaultApi",
               routeTemplate: "api/{controller}/{id}",
               defaults: new { id = RouteParameter.Optional }
           );
        }
    }
}

控制器

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

namespace Hzb.File.Controllers
{
    public class TestController : ApiController
    {

        [HttpGet]
        public string SimpleGet(int id, string name, DateTime bir)
        {
            return "id:" + id + " name:" + name + " time:" + bir.ToString();
        }

        [HttpGet]
        public string GetSendModel([FromUri] Person per)
        {
            return "id:" + per.ID + " name:" + per.Name + " time:" + per.CreateTime.ToString();
        }

        [HttpGet]
        public string GetSendModel(string strQuery)
        {
            Person per = JsonConvert.DeserializeObject<Person>(strQuery);
            return "id:" + per.ID + " name:" + per.Name + " time:" + per.CreateTime.ToString();
        }


        [HttpPost]
        public string PostOneData([FromBody]string param)
        {
            return param;
        }

        [HttpPost]
        public string PostManyData([FromBody]string call)
        {
            return call;
        }

        [HttpPost]
        public string PostManyData2()
        {
            string name = HttpContext.Current.Request.Form["name"];
            string des = HttpContext.Current.Request.Form["des"];
            return name + " " + des;
        }


        [HttpPost]
        public string PostModel(dynamic per)
        {
            return "id:" + per.ID + " name:" + per.Name + " time:" + per.CreateTime.ToString();
        } 
    }


    public class Person
    {
        /// <summary>  
        /// 主鍵Id  
        /// </summary>  
        public string ID { get; set; }

        /// <summary>  
        /// 充電設備名稱  
        /// </summary>  
        public string Name { get; set; }

        /// <summary>  
        /// 充電設備描述  
        /// </summary>  
        public string Des { get; set; }

        /// <summary>  
        /// 創建時間  
        /// </summary>  
        public DateTime CreateTime { get; set; }
    }  
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章