Asp.Net WebApi+JQuery Ajax的Get請求整理
一、總結
1.Asp.Net WebApi默認不支持Get請求,需要在Action方法上指定[HttpGet], 除非Action方法以‘Get’開頭。
2.默認路由中,沒有指定action,如果想路由到action不要手動指定
3.WebApi返回值的json對象,使用$.get 接收返回值,不需要手動反序列化處理
4.WebApi的Get請求中,Action可以接收多個參數
二、代碼驗證說明
1.默認不支持Get請求,需要在Action上指定請求類型[HttpGet]
[HttpGet] public string ShowName(string name) { return $"您傳入的名字:‘{name}’"; }
異常內容:
2.默認路由中沒有action參數處理
config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional }, constraints:new {id=@"\d+" } );
可以手動添加處理
config.Routes.MapHttpRoute( name: "DefaultApi2", routeTemplate: "api/{controller}/{action}", defaults: new { action = "Index" } );
3.WebApi的返回值都是json數據類型,JQuery中的Ajax會自動識別為json對象,不需要手動反序列化
[HttpGet] public object ShowName3(string name, int age) { return new { name = name, age = age, success = true }; }
相應結果:
返回字典類型:
[HttpGet] public Dictionary<string, string> GetList1(bool IsShow) { Dictionary<string, string> dict = new Dictionary<string, string>(); if (IsShow) { dict.Add("name1", "張三"); dict.Add("name2", "李四"); } return dict; }
JavaScript代碼:
$.get('/api/user/getlist1', { isshow: true }, function (data) { console.info(data); alert(data); }); $.get('/api/user/showname2', { name: '張三豐', age:19 }, function (data) { console.info(data); alert(data); });
Asp.Net WebApi+AngularJS $http的Get請求整理
1.WebApi,相應結果為json對象,不需要手動發序列化處理
//WebApi,相應結果為json對象,不需要手動發序列化處理 $http.get('/api/user/showname3', { params: { name: '張三', age: '15' } }).then(function (result) { //正確請求成功時處理 console.info(result); alert(result.data.name); }).catch(function (result) { //捕捉錯誤處理 console.info(result); alert(result.data.Message); });
$http.get('/api/user/getlist1', { params: { isshow: true } }).then(function (result) { console.info(result); console.info(result.data); }).catch(function (err) { console.info(err); alert(err.data.Message); });
更多: