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; }
    }  
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值