WebAPI笔记:前端和后端调用webapi测试案例

测试代码链接


简单了解参数绑定
Web API控制器中的操作方法可以有一个或多个不同类型的参数。它可以是基本类型,也可以是复杂类型。
Web API根据参数类型将操作方法参数绑定到URL的查询字符串或请求主体request body。
默认情况下,如果参数类型是.net基本类型,比如int、bool、double、string、GUID、DateTime、decimal或任何其他可以从string类型转换的类型,那么它将设置查询字符串中的参数值。
如果参数类型是复杂类型,那么默认情况下,Web API尝试从请求体获取值。

查询字符串参数名和操作方法参数名必须相同(不区分大小写)。如果名称不匹配,则不会设置参数的值。参数的顺序可以不同。

Web API将从请求主体中提取JSON对象,并自动将其转换为复杂对象,因为JSON对象属性的名称与Student类属性的名称相匹配(不区分大小写)。
控制器方法包含了基本类型参数和复杂类型参数。因此,在默认情况下,Web API将从查询字符串中获取基本数据类型参数,从请求主体中获取复杂类型参数。
Post操作方法不能包含多个复杂类型参数,因为最多允许从请求主体读取一个参数。

[FromUri] and [FromBody]
在默认情况下,Web API从查询字符串中获取原语参数的值,从请求主体中获取复杂类型参数。但是,如果我们想要改变这种默认行为呢?
使用[FromUri]属性强制Web API从查询字符串中获取复杂类型的值,使用[FromBody]属性从请求主体中获取原始类型的值,与默认规则相反。
使用[FromUri]属性时复杂类型属性的名称和查询字符串参数必须匹配。
使用[FromBody]属性只能应用于操作方法的一个基本参数。它不能应用于同一动作方法的多个基本参数。


前端调用webapi。测试案例SecondWebApi
通过调试了解webapi传递参数和数据获取
Http协议:无状态的协议 客户端和服务端就是一次性的
客户端->服务端:request header body 文字描述了数据信息,传输内容字符串
服务端->客户端:response header body 解析字符串,拿到关注的信息,完成业务操作,返回字符串,
实例化参数,参数只有两个来源:地址参数;表单参数;
调用方法的参数,都是源于这个解析,其实不解析也都能拿到的,比如HttpContext.Current.Request
参数绑定其实就是webapi遵循自己规则识别参数,也可以重写绑定 IBinder,但是没必要去折腾

后端调用webapi案例 在单元测试UnitTestProject.WebApiTest中调试验证
调用WebApi就是模拟Http请求,httpwebrequest/httpclient


定义WebApi路由规则

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

namespace SecondWebApi
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API 配置和服务

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

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

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


WebApi测试代码

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

namespace SecondWebApi.Controllers
{

    public class UsersController : ApiController
    {
        private List<Users> _userList = null;

        public UsersController()
        {
            _userList = new List<Users>
            {
                 new Users {UserID = 1, UserName = "Superman", UserEmail = "[email protected]"},
                 new Users {UserID = 2, UserName = "Spiderman", UserEmail = "[email protected]"},
                 new Users {UserID = 3, UserName = "Batman", UserEmail = "[email protected]"}
            };
        }
        #region HttpGet
        [HttpGet]
        public IEnumerable<Users> Get()
        {
            return _userList;
        }

        [HttpGet]
        public Users GetUserByID(int id)
        {
            string idParam = HttpContext.Current.Request.QueryString["id"];

            var user = _userList.FirstOrDefault(users => users.UserID == id);
            if (user == null)
            {
                throw new HttpResponseException(HttpStatusCode.NotFound);
            }
            return user;
        }

        [HttpGet]
        public IEnumerable<Users> GetUserByName(string userName)
        {
            string userNameParam = HttpContext.Current.Request.QueryString["userName"];

            return _userList.Where(p => string.Equals(p.UserName, userName, StringComparison.OrdinalIgnoreCase));
        }

        [HttpGet]
        public IEnumerable<Users> GetUserByNameId(string userName, int id)
        {
            string idParam = HttpContext.Current.Request.QueryString["id"];
            string userNameParam = HttpContext.Current.Request.QueryString["userName"];

            return _userList.Where(p => string.Equals(p.UserName, userName, StringComparison.OrdinalIgnoreCase));
        }

        [HttpGet]
        public IEnumerable<Users> GetUserByModel(Users user)
        {
            string idParam = HttpContext.Current.Request.QueryString["Userid"];
            string userNameParam = HttpContext.Current.Request.QueryString["UserName"];
            string emai = HttpContext.Current.Request.QueryString["UserEmail"];

            return _userList;
        }

        [HttpGet]
        public IEnumerable<Users> GetUserByModelUri([FromUri]Users user)
        {
            string idParam = HttpContext.Current.Request.QueryString["Userid"];
            string userNameParam = HttpContext.Current.Request.QueryString["userName"];
            string emai = HttpContext.Current.Request.QueryString["UserEmail"];

            return _userList;
        }

        [HttpGet]
        public IEnumerable<Users> GetUserByModelSerialize(string userString)
        {
            Users user = JsonConvert.DeserializeObject<Users>(userString);
            return _userList;
        }

        //[HttpGet]
        public IEnumerable<Users> GetUserByModelSerializeWithoutGet(string userString)
        {
            Users user = JsonConvert.DeserializeObject<Users>(userString);
            return _userList;
        }
        /// 
        /// 方法名以Get开头,WebApi会自动默认这个请求就是get请求,而如果你以其他名称开头而又不标注方法的请求方式,那么这个时候服务器虽然找到了这个方法,但是由于请求方式不确定,所以直接返回给你405——方法不被允许的错误。
        /// 最后结论:所有的WebApi方法最好是加上请求的方式([HttpGet]/[HttpPost]/[HttpPut]/[HttpDelete]),不要偷懒,这样既能防止类似的错误,也有利于方法的维护,别人一看就知道这个方法是什么请求。
        /// 
        /// 
        /// 
        public IEnumerable<Users> NoGetUserByModelSerializeWithoutGet(string userString)
        {
            Users user = JsonConvert.DeserializeObject<Users>(userString);
            return _userList;
        }
        #endregion HttpGet

        #region HttpPost
        [HttpPost]
        public Users RegisterNone()
        {
            return _userList.FirstOrDefault();
        }

        [HttpPost]
        public Users RegisterNoKey([FromBody]int id)
        {
            string idParam = HttpContext.Current.Request.Form["id"];

            var user = _userList.FirstOrDefault(users => users.UserID == id);
            if (user == null)
            {
                throw new HttpResponseException(HttpStatusCode.NotFound);
            }
            return user;
        }

        //POST api/Users/register
        //只接受一个参数的需要不给key才能拿到
        [HttpPost]
        public Users Register([FromBody]int id)//可以来自FromBody   FromUri
                                               //public Users Register(int id)//可以来自url
        {
            string idParam = HttpContext.Current.Request.Form["id"];

            var user = _userList.FirstOrDefault(users => users.UserID == id);
            if (user == null)
            {
                throw new HttpResponseException(HttpStatusCode.NotFound);
            }
            return user;
        }

        [HttpPost]
        public Users RegisterUser(Users user)//可以来自FromBody   FromUri
        {
            string idParam = HttpContext.Current.Request.Form["UserID"];
            string nameParam = HttpContext.Current.Request.Form["UserName"];
            string emailParam = HttpContext.Current.Request.Form["UserEmail"];

            //var userContent = base.ControllerContext.Request.Content.ReadAsFormDataAsync().Result;
            var stringContent = base.ControllerContext.Request.Content.ReadAsStringAsync().Result;
            return user;
        }


        [HttpPost]
        public string RegisterObject(JObject jData)//可以来自FromBody   FromUri
        {
            string idParam = HttpContext.Current.Request.Form["User[UserID]"];
            string nameParam = HttpContext.Current.Request.Form["User[UserName]"];
            string emailParam = HttpContext.Current.Request.Form["User[UserEmail]"];
            string infoParam = HttpContext.Current.Request.Form["info"];
            dynamic json = jData;
            JObject jUser = json.User;
            string info = json.Info;
            var user = jUser.ToObject<Users>();

            return string.Format("{0}_{1}_{2}_{3}", user.UserID, user.UserName, user.UserEmail, info);
        }

        [HttpPost]
        public string RegisterObjectDynamic(dynamic dynamicData)//可以来自FromBody   FromUri
        {
            string idParam = HttpContext.Current.Request.Form["User[UserID]"];
            string nameParam = HttpContext.Current.Request.Form["User[UserName]"];
            string emailParam = HttpContext.Current.Request.Form["User[UserEmail]"];
            string infoParam = HttpContext.Current.Request.Form["info"];
            dynamic json = dynamicData;
            JObject jUser = json.User;
            string info = json.Info;
            var user = jUser.ToObject<Users>();

            return string.Format("{0}_{1}_{2}_{3}", user.UserID, user.UserName, user.UserEmail, info);
        }
        #endregion HttpPost

        #region HttpPut
        [HttpPut]
        public Users RegisterNonePut()
        {
            return _userList.FirstOrDefault();
        }

        [HttpPut]
        public Users RegisterNoKeyPut([FromBody]int id)
        {
            string idParam = HttpContext.Current.Request.Form["id"];

            var user = _userList.FirstOrDefault(users => users.UserID == id);
            if (user == null)
            {
                throw new HttpResponseException(HttpStatusCode.NotFound);
            }
            return user;
        }

        //POST api/Users/registerPut
        //只接受一个参数的需要不给key才能拿到
        [HttpPut]
        public Users RegisterPut([FromBody]int id)//可以来自FromBody   FromUri
                                                  //public Users Register(int id)//可以来自url
        {
            string idParam = HttpContext.Current.Request.Form["id"];

            var user = _userList.FirstOrDefault(users => users.UserID == id);
            if (user == null)
            {
                throw new HttpResponseException(HttpStatusCode.NotFound);
            }
            return user;
        }

        [HttpPut]
        public Users RegisterUserPut(Users user)//可以来自FromBody   FromUri
        {
            string idParam = HttpContext.Current.Request.Form["UserID"];
            string nameParam = HttpContext.Current.Request.Form["UserName"];
            string emailParam = HttpContext.Current.Request.Form["UserEmail"];

            //var userContent = base.ControllerContext.Request.Content.ReadAsFormDataAsync().Result;
            var stringContent = base.ControllerContext.Request.Content.ReadAsStringAsync().Result;
            return user;
        }

        [HttpPut]
        public string RegisterObjectPut(JObject jData)//可以来自FromBody   FromUri
        {
            string idParam = HttpContext.Current.Request.Form["User[UserID]"];
            string nameParam = HttpContext.Current.Request.Form["User[UserName]"];
            string emailParam = HttpContext.Current.Request.Form["User[UserEmail]"];
            string infoParam = HttpContext.Current.Request.Form["info"];
            dynamic json = jData;
            JObject jUser = json.User;
            string info = json.Info;
            var user = jUser.ToObject<Users>();

            return string.Format("{0}_{1}_{2}_{3}", user.UserID, user.UserName, user.UserEmail, info);
        }

        [HttpPut]
        public string RegisterObjectDynamicPut(dynamic dynamicData)//可以来自FromBody   FromUri
        {
            string idParam = HttpContext.Current.Request.Form["User[UserID]"];
            string nameParam = HttpContext.Current.Request.Form["User[UserName]"];
            string emailParam = HttpContext.Current.Request.Form["User[UserEmail]"];
            string infoParam = HttpContext.Current.Request.Form["info"];
            dynamic json = dynamicData;
            JObject jUser = json.User;
            string info = json.Info;
            var user = jUser.ToObject<Users>();

            return string.Format("{0}_{1}_{2}_{3}", user.UserID, user.UserName, user.UserEmail, info);
        }
        #endregion HttpPut

        #region HttpDelete
        [HttpDelete]
        public Users RegisterNoneDelete()
        {
            return _userList.FirstOrDefault();
        }

        [HttpDelete]
        public Users RegisterNoKeyDelete([FromBody]int id)
        {
            string idParam = HttpContext.Current.Request.Form["id"];

            var user = _userList.FirstOrDefault(users => users.UserID == id);
            if (user == null)
            {
                throw new HttpResponseException(HttpStatusCode.NotFound);
            }
            return user;
        }

        //POST api/Users/registerDelete
        //只接受一个参数的需要不给key才能拿到
        [HttpDelete]
        public Users RegisterDelete([FromBody]int id)//可以来自FromBody   FromUri
                                                     //public Users Register(int id)//可以来自url
        {
            string idParam = HttpContext.Current.Request.Form["id"];

            var user = _userList.FirstOrDefault(users => users.UserID == id);
            if (user == null)
            {
                throw new HttpResponseException(HttpStatusCode.NotFound);
            }
            return user;
        }

        [HttpDelete]
        public Users RegisterUserDelete(Users user)//可以来自FromBody   FromUri
        {
            string idParam = HttpContext.Current.Request.Form["UserID"];
            string nameParam = HttpContext.Current.Request.Form["UserName"];
            string emailParam = HttpContext.Current.Request.Form["UserEmail"];

            //var userContent = base.ControllerContext.Request.Content.ReadAsFormDataAsync().Result;
            var stringContent = base.ControllerContext.Request.Content.ReadAsStringAsync().Result;
            return user;
        }


        [HttpDelete]
        public string RegisterObjectDelete(JObject jData)//可以来自FromBody   FromUri
        {
            string idParam = HttpContext.Current.Request.Form["User[UserID]"];
            string nameParam = HttpContext.Current.Request.Form["User[UserName]"];
            string emailParam = HttpContext.Current.Request.Form["User[UserEmail]"];
            string infoParam = HttpContext.Current.Request.Form["info"];
            dynamic json = jData;
            JObject jUser = json.User;
            string info = json.Info;
            var user = jUser.ToObject<Users>();

            return string.Format("{0}_{1}_{2}_{3}", user.UserID, user.UserName, user.UserEmail, info);
        }

        [HttpDelete]
        public string RegisterObjectDynamicDelete(dynamic dynamicData)//可以来自FromBody   FromUri
        {
            string idParam = HttpContext.Current.Request.Form["User[UserID]"];
            string nameParam = HttpContext.Current.Request.Form["User[UserName]"];
            string emailParam = HttpContext.Current.Request.Form["User[UserEmail]"];
            string infoParam = HttpContext.Current.Request.Form["info"];
            dynamic json = dynamicData;
            JObject jUser = json.User;
            string info = json.Info;
            var user = jUser.ToObject<Users>();

            return string.Format("{0}_{1}_{2}_{3}", user.UserID, user.UserName, user.UserEmail, info);
        }
        #endregion HttpDelete
    }
}


前端调用WebApi测试代码

<div class="jumbotron">
    <h1>ASP.NET</h1>
    <p class="lead">ASP.NET is a free web framework for building great Web sites and Web applications using HTML, CSS, and JavaScript.</p>
    <p><a href="https://asp.net" class="btn btn-primary btn-lg">Learn more &raquo;</a></p>
</div>
<div class="row">
    <div class="col-md-4">
        <h2>Getting started</h2>
        <p>
            ASP.NET Web API is a framework that makes it easy to build HTTP services that reach
            a broad range of clients, including browsers and mobile devices. ASP.NET Web API
            is an ideal platform for building RESTful applications on the .NET Framework.
        </p>
        <p><a class="btn btn-default" href="https://go.microsoft.com/fwlink/?LinkId=301870">Learn more &raquo;</a></p>
    </div>
    <div class="col-md-4">
        <h2>Get more libraries</h2>
        <p>NuGet is a free Visual Studio extension that makes it easy to add, remove, and update libraries and tools in Visual Studio projects.</p>
        <p><a class="btn btn-default" href="https://go.microsoft.com/fwlink/?LinkId=301871">Learn more &raquo;</a></p>
    </div>
    <div class="col-md-4">
        <h2>Web Hosting</h2>
        <p>You can easily find a web hosting company that offers the right mix of features and price for your applications.</p>
        <p><a class="btn btn-default" href="https://go.microsoft.com/fwlink/?LinkId=301872">Learn more &raquo;</a></p>
    </div>
</div>

<form  method="post" action="">
    <div class="row">
        <div class="col-md-5">
            <h2>Test </h2>

            <p><input type="text" id="txtId" name="id" /> </p>
            <p>
                <input type="button" id="btnGet1" value="Get1" />
                <input type="button" id="btnGet2" value="Get2" />
                <input type="button" id="btnGet3" value="Get3" />
                <input type="button" id="btnGet4" value="Get4" />
            </p>
            <p>
                <input type="button" id="btnGet5" value="Get5" />
                <input type="button" id="btnGet6" value="Get6" />
                <input type="button" id="btnGet7" value="Get7" />
                <input type="button" id="btnGet8" value="Get8" />
                <input type="button" id="btnGet9" value="Get9" />
            </p>

            <p>
                <input type="button" id="btnPost1" value="Post1" />
                <input type="button" id="btnPost2" value="Post2" />
                <input type="button" id="btnPost3" value="Post3" />
                <input type="button" id="btnPost4" value="Post4" />
            </p>
            <p>
                <input type="button" id="btnPost5" value="Post5" />
                <input type="button" id="btnPost6" value="Post6" />
            </p>
            <p>
                <input type="button" id="btnPut1" value="Put1" />
                <input type="button" id="btnPut2" value="Put2" />
                <input type="button" id="btnPut3" value="Put3" />
                <input type="button" id="btnPut4" value="Put4" />
                <input type="button" id="btnPut5" value="Put5" />
                <input type="button" id="btnPut6" value="Put6" />
            </p>
        </div>
    </div>
</form>

@section scripts{
    <script>
        $(function () {
            var user = { UserID: "11", UserName: "Eleven", UserEmail: "[email protected]" };
            var info = "this is muti model";
            var ids = ["1", "2", "3", "4"];
            var userList = [
                { UserID: "111", UserName: "Eleven1", UserEmail: "[email protected]" },
                { UserID: "112", UserName: "Eleven2", UserEmail: "[email protected]" },
                { UserID: "113", UserName: "Eleven3", UserEmail: "[email protected]" }
            ];
            //get请求 参数拼装到url  Get最长是1024 参数不要太多
            $("#btnGet1").on("click", function () {//单个参数 指向接口,参数匹配的,大小写不区分
                $.ajax({ url: "/userapi/users/GetuserByName", type: "get", data: { "userName": "Superman" }, success: function (data) { alert(data); console.log(data); }, datatype: "json" });
            });
            $("#btnGet2").on("click", function () {//单个参数 获取输入信息
                $.ajax({ url: "/userapi/users/GetUserById", type: "get", data: { "id": $("#txtId").val() }, success: function (data) { alert(data); console.log(data); }, datatype: "json" });
            });
            $("#btnGet3").on("click", function () {//两个参数
                $.ajax({ url: "/userapi/users/GetUserByNameId", type: "get", data: { "userName": "Superman", "id": $("#txtId").val() }, success: function (data) { alert(data); console.log(data); }, datatype: "json" });
            });
            $("#btnGet4").on("click", function () {//无参数
                $.ajax({ url: "/userapi/users/Get", type: "get", data: "", success: function (data) { alert(data); console.log(data); }, datatype: "json" });
            });
            $("#btnGet5").on("click", function () {//传递实体 json对象 json格式  默认[FromBody]是无法获取参数
                $.ajax({ url: "/userapi/users/GetUserByModel", type: "get", data: user, success: function (data) { alert(data); console.log(data); }, datatype: "json" });
            });
            $("#btnGet6").on("click", function () {//传递实体 带[FromUri]可以自动绑定
                $.ajax({ url: "/userapi/users/GetUserByModelUri", type: "get", data: user, success: function (data) { alert(data); console.log(data); }, datatype: "json" });
            });
            $("#btnGet7").on("click", function () {//传递实体,序列化后传递  对象之间换成字符串(性能几乎无差别)
                $.ajax({ url: "/userapi/users/GetUserByModelSerialize", type: "get", data: { userString: JSON.stringify(user) }, success: function (data) { alert(data); console.log(data); }, datatype: "json" });
            });
            $("#btnGet8").on("click", function () {//传递实体,序列化后传递   没有[HttpGet],但是有开头
                $.ajax({ url: "/userapi/users/GetUserByModelSerializeWithoutGet", type: "get", data: { userString: JSON.stringify(user) }, success: function (data) { alert(data); console.log(data); }, datatype: "json" });
            });
            $("#btnGet9").on("click", function () {//传递实体,序列化后传递  405 Method Not Allowed    不带httpget需要用get开头
                $.ajax({ url: "/userapi/users/NoGetUserByModelSerializeWithoutGet", type: "get", data: { userString: JSON.stringify(user) }, success: function (data) { alert(data); console.log(data); }, datatype: "json" });
            });

            //post 参数是form参数
            //post请求 [FromBody] 绑定表单参数,不是按照key-value   =value    只有一个数据不要key
            //想传递key-value  对象倒是可以的
            //想传递json字符串,要配置contenttype
            $("#btnPost1").on("click", function () {//单个值传递,json数据不要key,这样后台才能获取
                $.ajax({ url: "/userapi/users/RegisterNoKey", type: "post", data: { "": $("#txtId").val() }, success: function (data) { alert(data); console.log(data); }, datatype: "json" });
            });
            $("#btnPost2").on("click", function () {//key-value形式后台拿不到这个参数,但是可以直接访问
                $.ajax({ url: "/userapi/users/Register", type: "post", data: { "id": $("#txtId").val() }, success: function (data) { alert(data); console.log(data); }, datatype: "json" });
            });
            $("#btnPost3").on("click", function () {//传递json格式的,后台可以用实体接收
                $.ajax({ url: "/userapi/users/RegisterUser", type: "post", data: user, success: function (data) { alert(data); console.log(data); }, datatype: "json" });
            });
            $("#btnPost4").on("click", function () {//传递json序列化后的格式,后台可以用实体接收,需要指定contentType
                $.ajax({ url: "/userapi/users/RegisterUser", type: "post", data: JSON.stringify(user), success: function (data) { alert(data); console.log(data); }, datatype: "json", contentType: 'application/json' });
            });
            //FormCollection可以收藏任何参数
            //传递2个参数  包一个json对象,后台也得建一个实体
            $("#btnPost5").on("click", function () {//JObject接收
                $.ajax({ url: "/userapi/users/RegisterObject", type: "post", data: { "User": user, "Info": info }, success: function (data) { alert(data); console.log(data); }, datatype: "json" });
            });
            $("#btnPost6").on("click", function () {//Dynamic
                $.ajax({ url: "/userapi/users/RegisterObjectDynamic", type: "post", data: { "User": user, "Info": info }, success: function (data) { alert(data); console.log(data); }, datatype: "json" });
            });
            //数组 ids   后台直接声明 string[] ids 可以获取的
            //数组 userList     字符串反序列化contenttype    直接传递对象 后台直接List


            $("#btnPut1").on("click", function () {//单个值传递,json数据不要key,这样后台才能获取
                $.ajax({ url: "/userapi/users/RegisterNoKeyPut", type: "put", data: { "": $("#txtId").val() }, success: function (data) { alert(data); console.log(data); }, datatype: "json" });
            });
            $("#btnPut2").on("click", function () {//key-value形式后台拿不到
                $.ajax({ url: "/userapi/users/RegisterPut", type: "put", data: { "id": $("#txtId").val() }, success: function (data) { alert(data); console.log(data); }, datatype: "json" });
            });
            $("#btnPut3").on("click", function () {//传递json格式的,后台可以用实体接收
                $.ajax({ url: "/userapi/users/RegisterUserPut", type: "put", data: user, success: function (data) { alert(data); console.log(data); }, datatype: "json" });
            });

            $("#btnPut4").on("click", function () {//传递json序列化后的格式,后台可以用实体接收,需要指定contentType
                $.ajax({ url: "/userapi/users/RegisterUserPut", type: "put", data: JSON.stringify(user), success: function (data) { alert(data); console.log(data); }, datatype: "json", contentType: 'application/json', });
            });

            $("#btnPut5").on("click", function () {//JObject接收
                $.ajax({ url: "/userapi/users/RegisterObjectPut", type: "put", data: { "User": user, "Info": info }, success: function (data) { alert(data); console.log(data); }, datatype: "json" });
            });
            $("#btnPut6").on("click", function () {//Dynamic  失败了
                $.ajax({ url: "/userapi/users/RegisterObjectDynamicPut", type: "put", data: { "User": user, "Info": info }, success: function (data) { alert(data); console.log(data); }, datatype: "json", contentType: 'application/json' });
            });

            //delete一样 type换成delete





            //跨域测试
            //microsoft.aspnet.webapi.cors
            jQuery.support.cors = true;
            var location = "http://localhost:9008";
            $("#btnGetCors1").on("click", function () {
                $.ajax({ url: location + "/userapi/users/GetUserByID", type: "get", data: { "id": 1 }, success: function (data) { alert(data); }, datatype: "json" });
            });

        });
    </script>
}

单元测试模拟后端调用WebApi测试代码

using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Text;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace UnitTestProject
{


    /// 
    /// 调用WebApi就是模拟Http请求,httpwebrequest/httpclient
    /// 
    [TestClass]
    public class WebApiTest
    {
        [TestMethod]
        public void TestMethod1()
        {
            var result1 = this.GetClient();
            var result2 = this.GetWebQuest();
            var result3 = this.PostClient();
            var result4 = this.PostWebQuest();
            var result5 = this.PutClient();
            var result6 = this.PutWebQuest();
            var result7 = this.DeleteClient();//传值只能是url
            var result8 = this.DeleteWebQuest();

        }


        #region HttpClient Get
        /// 
        /// HttpClient实现Get请求
        /// 
        private string GetClient()
        {
            //string url = "https://localhost:44315/userapi/users/GetUserByName?username=superman";
            //string url = "https://localhost:44315/userapi/users/GetUserByID?id=1";
            //string url = "https://localhost:44315/userapi/users/GetUserByNameId?userName=Superman&id=1";
            //string url = "https://localhost:44315/userapi/users/Get";
            //string url = "https://localhost:44315/userapi/users/GetUserByModel?UserID=11&UserName=Eleven&UserEmail=57265177%40qq.com";
            //string url = "https://localhost:44315/userapi/users/GetUserByModelUri?UserID=11&UserName=Eleven&UserEmail=57265177%40qq.com";
            string url = "https://localhost:44315/userapi/users/GetUserByModelSerialize?userString=%7B%22UserID%22%3A%2211%22%2C%22UserName%22%3A%22Eleven%22%2C%22UserEmail%22%3A%2257265177%40qq.com%22%7D";
            //string url = "https://localhost:44315/userapi/users/GetUserByModelSerializeWithoutGet?userString=%7B%22UserID%22%3A%2211%22%2C%22UserName%22%3A%22Eleven%22%2C%22UserEmail%22%3A%2257265177%40qq.com%22%7D";
            //string url = "https://localhost:44315/userapi/users/NoGetUserByModelSerializeWithoutGet?userString=%7B%22UserID%22%3A%2211%22%2C%22UserName%22%3A%22Eleven%22%2C%22UserEmail%22%3A%2257265177%40qq.com%22%7D";
            
            
            //var handler = new HttpClientHandler();//{ AutomaticDecompression = DecompressionMethods.GZip };
            //using (var http = new HttpClient(handler))
            //{
            //    var response = http.GetAsync(url).Result;//拿到异步结果
            //    Console.WriteLine(response.StatusCode); //确保HTTP成功状态值
            //    //await异步读取最后的JSON(注意此时gzip已经被自动解压缩了,因为上面的AutomaticDecompression = DecompressionMethods.GZip)
            //    return response.Content.ReadAsStringAsync().Result;
            //}


            /// HttpClient
            /// using (var http = new HttpClient(handler)) 不太好 tcp其实并不能立即释放掉
            /// 如果高并发式的这样操作,会出现资源不够  积极拒绝
            /// HttpClient内部有个连接池,各个请求是隔开的,可以复用链接的 实际应该单例一下

            var http = HttpClientFactory.GetHttpClient();
            var response = http.GetAsync(url).Result;//拿到异步结果
            Console.WriteLine(response.StatusCode); //确保HTTP成功状态值
                                                    //await异步读取最后的JSON(注意此时gzip已经被自动解压缩了,因为上面的AutomaticDecompression = DecompressionMethods.GZip)
            return response.Content.ReadAsStringAsync().Result;
        }


        /// 
        /// 要求HttpClient的实例化都从这里来  全局只要一个实例,不要using
        /// 各个请求是隔开的,可以复用链接的 
        /// 
        public class HttpClientFactory
        {
            private static HttpClient _HttpClient = null;
            static HttpClientFactory()
            {
                _HttpClient = new HttpClient(new HttpClientHandler());
            }
            public static HttpClient GetHttpClient()
            {
                return _HttpClient;
            }
        }
        #endregion

        #region HttpWebRequest实现Get请求
        /// 
        /// HttpWebRequest实现Get请求
        /// 
        private string GetWebQuest()
        {
            //string url = "https://localhost:44315/userapi/users/GetUserByName?username=superman";
            //string url = "https://localhost:44315/userapi/users/GetUserByID?id=1";
            //string url = "https://localhost:44315/userapi/users/GetUserByNameId?userName=Superman&id=1";
            //string url = "https://localhost:44315/userapi/users/Get";
            //string url = "https://localhost:44315/userapi/users/GetUserByModel?UserID=11&UserName=Eleven&UserEmail=57265177%40qq.com";
            //string url = "https://localhost:44315/userapi/users/GetUserByModelUri?UserID=11&UserName=Eleven&UserEmail=57265177%40qq.com";
            string url = "https://localhost:44315/userapi/users/GetUserByModelSerialize?userString=%7B%22UserID%22%3A%2211%22%2C%22UserName%22%3A%22Eleven%22%2C%22UserEmail%22%3A%2257265177%40qq.com%22%7D";
            //string url = "https://localhost:44315/userapi/users/GetUserByModelSerializeWithoutGet?userString=%7B%22UserID%22%3A%2211%22%2C%22UserName%22%3A%22Eleven%22%2C%22UserEmail%22%3A%2257265177%40qq.com%22%7D";
            //string url = "https://localhost:44315/userapi/users/NoGetUserByModelSerializeWithoutGet?userString=%7B%22UserID%22%3A%2211%22%2C%22UserName%22%3A%22Eleven%22%2C%22UserEmail%22%3A%2257265177%40qq.com%22%7D";

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Timeout = 30 * 1000;

            //request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.118 Safari/537.36";
            //request.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";
            string result = "";
            using (var res = request.GetResponse() as HttpWebResponse)
            {
                if (res.StatusCode == HttpStatusCode.OK)
                {
                    StreamReader reader = new StreamReader(res.GetResponseStream(), Encoding.UTF8);
                    result = reader.ReadToEnd();
                }
            }
            return result;
        }

        #endregion

        #region HttpClient实现Post请求
        /// 
        /// HttpClient实现Post请求
        /// 
        private string PostClient()
        {
            //string url = "https://localhost:44315/userapi/users/register";
            //Dictionary dic = new Dictionary()
            //{
            //    {"","1" }
            //};

            //string url = "https://localhost:44315/userapi/users/RegisterNoKey";
            //Dictionary dic = new Dictionary()
            //{
            //    {"","1" }
            //};

            //string url = "https://localhost:44315/userapi/users/RegisterUser";
            //Dictionary dic = new Dictionary()
            //{
            //    {"UserID","11" },
            //    {"UserName","Eleven" },
            //    {"UserEmail","[email protected]" },
            //};

            string url = "https://localhost:44315/userapi/users/RegisterObject";
            Dictionary<string, string> dic = new Dictionary<string, string>()
            {
                {"User[UserID]","11" },
                {"User[UserName]","Eleven" },
                {"User[UserEmail]","[email protected]" },
                {"Info","this is muti model" }
            };

            HttpClientHandler handler = new HttpClientHandler();
            using (var http = new HttpClient(handler))
            {
                //使用FormUrlEncodedContent做HttpContent
                var content = new FormUrlEncodedContent(dic);
                var response = http.PostAsync(url, content).Result;
                Console.WriteLine(response.StatusCode); //确保HTTP成功状态值
                return response.Content.ReadAsStringAsync().Result;
            }

        }
        #endregion

        #region  HttpWebRequest实现post请求
        /// 
        /// HttpWebRequest实现post请求
        /// 
        private string PostWebQuest()
        {
            //string url = "https://localhost:44315/userapi/users/register";
            //var postData = "1";

            //string url = "https://localhost:44315/userapi/users/RegisterNoKey";
            //var postData = "1";

            var user = new
            {
                UserID = "11",
                UserName = "Eleven",
                UserEmail = "[email protected]"
            };
            //string url = "https://localhost:44315/userapi/users/RegisterUser";
            //var postData = JsonHelper.ObjectToString(user);

            var userOther = new
            {
                User = user,
                Info = "this is muti model"
            };
            string url = "https://localhost:44315/userapi/users/RegisterObject";
            var postData = Newtonsoft.Json.JsonConvert.SerializeObject(userOther);

            var request = HttpWebRequest.Create(url) as HttpWebRequest;
            request.Timeout = 30 * 1000;//设置30s的超时
            //request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.118 Safari/537.36";
            request.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.89 Safari/537.36";
            request.ContentType = "application/json";
            request.Method = "POST";
            byte[] data = Encoding.UTF8.GetBytes(postData);
            request.ContentLength = data.Length;
            Stream postStream = request.GetRequestStream();
            postStream.Write(data, 0, data.Length);
            postStream.Close();

            string result = "";
            using (var res = request.GetResponse() as HttpWebResponse)
            {
                if (res.StatusCode == HttpStatusCode.OK)
                {
                    StreamReader reader = new StreamReader(res.GetResponseStream(), Encoding.UTF8);
                    result = reader.ReadToEnd();
                }
            }
            return result;
        }
        #endregion

        #region HttpClient实现Put请求
        /// 
        /// HttpClient实现Put请求
        /// 
        private string PutClient()
        {
            string url = "https://localhost:44315/userapi/users/RegisterPut";
            Dictionary<string, string> dic = new Dictionary<string, string>()
            {
                {"","1" }
            };

            //string url = "https://localhost:44315/userapi/users/RegisterNoKeyPut";
            //Dictionary dic = new Dictionary()
            //{
            //    {"","1" }
            //};

            //string url = "https://localhost:44315/userapi/users/RegisterUserPut";
            //Dictionary dic = new Dictionary()
            //{
            //    {"UserID","11" },
            //    {"UserName","Eleven" },
            //    {"UserEmail","[email protected]" },
            //};

            //string url = "https://localhost:44315/userapi/users/RegisterObjectPut";
            //Dictionary dic = new Dictionary()
            //{
            //    {"User[UserID]","11" },
            //    {"User[UserName]","Eleven" },
            //    {"User[UserEmail]","[email protected]" },
            //    {"Info","this is muti model" }
            //};

            HttpClientHandler handler = new HttpClientHandler();
            using (var http = new HttpClient(handler))
            {
                //使用FormUrlEncodedContent做HttpContent
                var content = new FormUrlEncodedContent(dic);
                var response = http.PutAsync(url, content).Result;
                Console.WriteLine(response.StatusCode); //确保HTTP成功状态值
                return response.Content.ReadAsStringAsync().Result;
            }

        }
        #endregion

        #region  HttpWebRequest实现put请求
        /// 
        /// HttpWebRequest实现put请求
        /// 
        private string PutWebQuest()
        {
            //string url = "https://localhost:44315/userapi/users/registerPut";
            //var postData = "1";

            //string url = "https://localhost:44315/userapi/users/RegisterNoKeyPut";
            //var postData = "1";

            var user = new
            {
                UserID = "11",
                UserName = "Eleven",
                UserEmail = "[email protected]"
            };
            //string url = "https://localhost:44315/userapi/users/RegisterUserPut";
            //var postData = JsonHelper.ObjectToString(user);

            var userOther = new
            {
                User = user,
                Info = "this is muti model"
            };
            string url = "https://localhost:44315/userapi/users/RegisterObjectPut";
            var postData = Newtonsoft.Json.JsonConvert.SerializeObject(userOther);

            var request = HttpWebRequest.Create(url) as HttpWebRequest;
            request.Timeout = 30 * 1000;//设置30s的超时
            //request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.118 Safari/537.36";
            request.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.89 Safari/537.36";
            request.ContentType = "application/json";
            request.Method = "PUT";
            byte[] data = Encoding.UTF8.GetBytes(postData);
            request.ContentLength = data.Length;
            Stream postStream = request.GetRequestStream();
            postStream.Write(data, 0, data.Length);
            postStream.Close();

            string result = "";
            using (var res = request.GetResponse() as HttpWebResponse)
            {
                if (res.StatusCode == HttpStatusCode.OK)
                {
                    StreamReader reader = new StreamReader(res.GetResponseStream(), Encoding.UTF8);
                    result = reader.ReadToEnd();
                }
            }
            return result;
        }
        #endregion

        #region HttpClient实现Delete请求
        /// 
        /// HttpClient实现Put请求
        /// 没放入数据
        /// 
        private string DeleteClient()
        {
            string url = "https://localhost:44315/userapi/users/RegisterDelete/1";
            Dictionary<string, string> dic = new Dictionary<string, string>()
            {
                {"","1" }
            };

            //string url = "https://localhost:44315/userapi/users/RegisterNoKeyDelete";
            //Dictionary dic = new Dictionary()
            //{
            //    {"","1" }
            //};

            //string url = "https://localhost:44315/userapi/users/RegisterUserDelete";
            //Dictionary dic = new Dictionary()
            //{
            //    {"UserID","11" },
            //    {"UserName","Eleven" },
            //    {"UserEmail","[email protected]" },
            //};

            //string url = "https://localhost:44315/userapi/users/RegisterObjectDelete";
            //Dictionary dic = new Dictionary()
            //{
            //    {"User[UserID]","11" },
            //    {"User[UserName]","Eleven" },
            //    {"User[UserEmail]","[email protected]" },
            //    {"Info","this is muti model" }
            //};

            HttpClientHandler handler = new HttpClientHandler();
            using (var http = new HttpClient(handler))
            {
                //使用FormUrlEncodedContent做HttpContent
                var content = new FormUrlEncodedContent(dic);
                var response = http.DeleteAsync(url).Result;
                Console.WriteLine(response.StatusCode); //确保HTTP成功状态值
                return response.Content.ReadAsStringAsync().Result;
            }
        }
        #endregion

        #region  HttpWebRequest实现put请求
        /// 
        /// HttpWebRequest实现put请求
        /// 
        private string DeleteWebQuest()
        {
            //string url = "https://localhost:44315/userapi/users/registerDelete";
            //var postData = "1";

            //string url = "https://localhost:44315/userapi/users/RegisterNoKeyDelete";
            //var postData = "1";

            var user = new
            {
                UserID = "11",
                UserName = "Eleven",
                UserEmail = "[email protected]"
            };
            //string url = "https://localhost:44315/userapi/users/RegisterUserDelete";
            //var postData = JsonHelper.ObjectToString(user);

            var userOther = new
            {
                User = user,
                Info = "this is muti model"
            };
            string url = "https://localhost:44315/userapi/users/RegisterObjectDelete";
            var postData = Newtonsoft.Json.JsonConvert.SerializeObject(userOther);

            var request = HttpWebRequest.Create(url) as HttpWebRequest;
            request.Timeout = 30 * 1000;//设置30s的超时
            //request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.118 Safari/537.36";
            request.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.89 Safari/537.36";
            request.ContentType = "application/json";
            request.Method = "Delete";
            byte[] data = Encoding.UTF8.GetBytes(postData);
            request.ContentLength = data.Length;
            Stream postStream = request.GetRequestStream();
            postStream.Write(data, 0, data.Length);
            postStream.Close();

            string result = "";
            using (var res = request.GetResponse() as HttpWebResponse)
            {
                if (res.StatusCode == HttpStatusCode.OK)
                {
                    StreamReader reader = new StreamReader(res.GetResponseStream(), Encoding.UTF8);
                    result = reader.ReadToEnd();
                }
            }
            return result;
        }
        #endregion
    }
}

你可能感兴趣的:(WebApi)