Ajax 調用Web API大全

 

目錄

首先配置一下WebApiConfig

調用無參數方法

Get

Get傳遞實體

GetUri傳遞實體

Get序列化後傳遞實體

Get請求失敗405

Post請求單個參數

Post請求多個參數

Post傳遞實體

Post序列化後傳遞實體

Post使用Jobject接收多個參數

Put請求單個參數

Put傳遞實體

Put序列化後傳遞實體

Put使用Jobject接收多個參數

 HttpDelete與HttpPut是一樣的就不寫了


首先配置一下WebApiConfig

         config.Routes.MapHttpRoute(
             name: "DefaultApi2",
             routeTemplate: "api/{controller}/{action}/{id}",
             defaults: new { id = RouteParameter.Optional }
         );//新增api路由到指定action
         config.Routes.MapHttpRoute(
               name: "DefaultApi",
               routeTemplate: "api/{controller}/{id}",
               defaults: new { id = RouteParameter.Optional }
           );

添加一個新的站點地圖,爲什麼要添加上面這個新的呢?

我們來看一下系統自動生成的地址:api/{controller}/{id}

簡單來說如果要訪問api的地址就需要在地址前加api然後是controller的名字最後是參數,沒錯沒有方法名稱,也就是說系統最開始生成的站點地址不需要尋找方法名稱,只需要給參數就可以了,但是如果調用無參數的方法就會找不到路徑,這個問題很尷尬,大家注意一下

調用無參數方法

   public class ValuesController : ApiController
    {
        [HttpGet]
        // GET api/values
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }
    }
function GetNoParameters() {
        var par = {         
        };
        $.ajax({
            type: "get",
            url: "/api/Values/Get",
            data: par,
            dataType: "json",
            success: function (data) {
                console.log(data);
            },
            error: function (e) {
                console.log(e);
            }
        });
    }

Get

[HttpGet]
public string Get(int id)
{
    return "value";
}
function Get() {
        var par = {
                    "id":1
                    };
        $.ajax({
            type: "get",
            url: "/api/Values/Get",
            data: par,
            dataType: "json",
            success: function (data) {
                console.log(data);
            },
            error: function (e) {
                console.log(e);
            }
        });
    }

Get傳遞實體

[HttpGet]
public IEnumerable<Users> GetUserByModel(Users user)
{
    //不能接到user的值,能接收到Request的值
    int idParam = Convert.ToInt32(HttpContext.Current.Request.QueryString["UserID"]);
    string userNameParam = HttpContext.Current.Request.QueryString["UserName"];
    string emai = HttpContext.Current.Request.QueryString["UserEmail"];           
    List<Users> _userList = new List<Users>
    {
        new Users {UserID = idParam, UserName = userNameParam, UserEmail = emai},
        new Users {UserID = idParam, UserName = userNameParam, UserEmail = emai},
        new Users {UserID = idParam, UserName = userNameParam, UserEmail = emai}
    };
    return _userList;
}
function GetModel() {
        var user = { UserID: 11, UserName: "小張", UserEmail: "[email protected]" };
        $.ajax({
            type: "get",
            url: "/api/Values/GetUserByModel",
            contentType: 'application/json',
            data: user,
            dataType: "json",
            success: function (data) {
                console.log(data);
            },
            error: function (e) {
                console.log(e);
            }
        });
    }

GetUri傳遞實體

        [HttpGet]
        public IEnumerable<Users> GetUserByModelUri([FromUri]Users user)
        {
            //能接到user的值,也能接收到Request的值
            int idParam = Convert.ToInt32(HttpContext.Current.Request.QueryString["UserID"]);
            string userNameParam = HttpContext.Current.Request.QueryString["UserName"];
            string emai = HttpContext.Current.Request.QueryString["UserEmail"];
            List<Users> _userList = new List<Users>
            {
                new Users {UserID = idParam, UserName = userNameParam, UserEmail = emai},
                new Users {UserID = idParam, UserName = userNameParam, UserEmail = emai},
                new Users {UserID = idParam, UserName = userNameParam, UserEmail = emai}
            };
            return _userList;
        }
function GetModelUri() {
        var user = { UserID: 11, UserName: "小張", UserEmail: "[email protected]" };
        $.ajax({
            type: "get",
            url: "/api/Values/GetUserByModelUri",
            contentType: 'application/json',
            data: user,
            dataType: "json",
            success: function (data) {
                console.log(data);
            },
            error: function (e) {
                console.log(e);
            }
        });
    }

Get序列化後傳遞實體

        [HttpGet]
        public IEnumerable<Users> GetUserByModelSerialize(string userString)
        {
            Users user = JsonConvert.DeserializeObject<Users>(userString);
            List<Users> _userList = new List<Users>();
            _userList.Add(user);
            return _userList;
        }
function GetUserByModelSerialize() {
        var user = { UserID: 11, UserName: "小張", UserEmail: "[email protected]" };
        $.ajax({
            type: "get",
            url: "/api/Values/GetUserByModelSerialize",
            contentType: 'application/json',
            data: {userString:JSON.stringify(user)},
            dataType: "json",
            success: function (data) {
                console.log(data);
            },
            error: function (e) {
                console.log(e);
            }
        });
    }

Get請求失敗405

方法名以Get開頭,WebApi會自動默認這個請求就是get請求,而如果你以其他名稱開頭而又不標註方法的請求方式,那麼這個時候服務器雖然找到了這個方法,但是由於請求方式不確定,所以直接返回給你405——方法不被允許的錯誤

要養成良好習慣加上請求的方式([HttpGet]/[HttpPost]/[HttpPut]/[HttpDelete])

        public IEnumerable<Users> XXXXXGetUserByModelSerialize(string userString)
        {
            Users user = JsonConvert.DeserializeObject<Users>(userString);
            List<Users> _userList = new List<Users>();
            _userList.Add(user);
            return _userList;
        }
function XXXXXGetUserByModelSerialize() {
        var user = { UserID: 11, UserName: "小張", UserEmail: "[email protected]" };
        $.ajax({
            type: "get",
            url: "/api/Values/XXXXXGetUserByModelSerialize",
            contentType: 'application/json',
            data: {userString:JSON.stringify(user)},
            dataType: "json",
            success: function (data) {
                console.log(data);
            },
            error: function (e) {
                console.log(e);
            }
        });
    }

Post請求單個參數

只接受一個參數的需要不給key才能拿到

        [HttpPost]
        public string Post([FromBody]string id)
        {
            return id;
        }
function Post() {
        var par = {
                    '':'1'
                    };
        $.ajax({
            type: "post",
            url: "/api/Values/Post",
            data: par,
            dataType: "json",
            success: function (data) {
                console.log(data);
            },
            error: function (e) {
                console.log(e);
            }
        });
    }

Post請求多個參數

別想了,老實用實體傳吧。或者試試Jobject

Post傳遞實體

        [HttpPost]
        public IEnumerable<Users> PostUserModel([FromBody]Users user)
        {
            //能接到user的值,能接收到Request的值
            int idParam = Convert.ToInt32(HttpContext.Current.Request.Form["UserID"]);
            string userNameParam = HttpContext.Current.Request.Form["UserName"];
            string emai = HttpContext.Current.Request.Form["UserEmail"];
            //不能收到值
            var stringContent = base.ControllerContext.Request.Content.ReadAsStringAsync().Result;
            List<Users> _userList = new List<Users>
            {
                new Users {UserID = idParam, UserName = userNameParam, UserEmail = emai},
                new Users {UserID = idParam, UserName = userNameParam, UserEmail = emai},
                new Users {UserID = idParam, UserName = userNameParam, UserEmail = emai}
            };
            return _userList;
        }
function PostUserModel() {
        var user = { UserID: 11, UserName: "小張", UserEmail: "[email protected]" };
        $.ajax({
            type: "post",
            url: "/api/Values/PostUserModel",
            data: user,
            dataType: "json",
            success: function (data) {
                console.log(data);
            },
            error: function (e) {
                console.log(e);
            }
        });
    }

Post序列化後傳遞實體

        [HttpPost]
        public IEnumerable<Users> PostUserModelSerialize([FromBody]Users user)
        {
            //能接到user的值,不能接收到Request的值
            int idParam = Convert.ToInt32(HttpContext.Current.Request.Form["UserID"]);
            string userNameParam = HttpContext.Current.Request.Form["UserName"];
            string emai = HttpContext.Current.Request.Form["UserEmail"];
            //不能收到值
            var stringContent = base.ControllerContext.Request.Content.ReadAsStringAsync().Result;
            List<Users> _userList = new List<Users>
            {
                new Users {UserID = idParam, UserName = userNameParam, UserEmail = emai},
                new Users {UserID = idParam, UserName = userNameParam, UserEmail = emai},
                new Users {UserID = idParam, UserName = userNameParam, UserEmail = emai}
            };
            return _userList;
        }

 不能寫參數名稱,必須寫contentType

function PostUserModelSerialize() {
        var user = { UserID: 11, UserName: "小張", UserEmail: "[email protected]" };
        $.ajax({
            type: "post",
            url: "/api/Values/PostUserModelSerialize",
            contentType: 'application/json',
            data: JSON.stringify(user),
            dataType: "json",
            success: function (data) {
                console.log(data);
            },
            error: function (e) {
                console.log(e);
            }
        });
    }

Post使用Jobject接收多個參數

        [HttpPost]
        public string PostModelObject([FromBody]JObject jData)
        {
            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);
        }
function PostModelObject() {
        var user = { UserID: 11, UserName: "小張", UserEmail: "[email protected]" };
        var info = "this is muti model";
        $.ajax({
            type: "post",
            url: "/api/Values/PostModelObject",
            data: {User:user,Info:info},
            dataType: "json",
            success: function (data) {
                console.log(data);
            },
            error: function (e) {
                console.log(e);
            }
        });
    }

Put請求單個參數

只接受一個參數的需要不給key才能拿到

        [HttpPut]
        public string Put([FromBody]int id)
        {
            return "";
        }
function Put() {
        var par = {
            '': '1'
        };
        $.ajax({
            type: "put",
            url: "/api/Values/Put",
            data: par,
            dataType: "json",
            success: function (data) {
                console.log(data);
            },
            error: function (e) {
                console.log(e);
            }
        });
    }

Put傳遞實體

        [HttpPut]
        public Users PutUserModel([FromBody]Users user)
        {
            //能接到user的值,能接收到Request的值
            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;
        }
function PutUserModel() {        
        var user = { UserID: 11, UserName: "小張", UserEmail: "[email protected]" };
        $.ajax({
            type: "put",
            url: "/api/Values/PutUserModel",
            data: user,
            dataType: "json",
            success: function (data) {
                console.log(data);
            },
            error: function (e) {
                console.log(e);
            }
        });
    }

Put序列化後傳遞實體

        [HttpPut]
        public Users PutUserModel([FromBody]Users user)
        {
            //能接到user的值,不能接收到Request的值
            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;
        }

 不能寫參數名稱,必須寫contentType

function PutUserModelSerialize() {        
        var user = { UserID: 11, UserName: "小張", UserEmail: "[email protected]" };
        $.ajax({
            type: "put",
            url: "/api/Values/PutUserModel",
            contentType: 'application/json',
            data: JSON.stringify(user),
            dataType: "json",
            success: function (data) {
                console.log(data);
            },
            error: function (e) {
                console.log(e);
            }
        });
    }

 

Put使用Jobject接收多個參數

        [HttpPut]
        public string PutModelObject([FromBody]JObject jData)
        {
            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);
        }
function PutModelObject() {
        var user = { UserID: 11, UserName: "小張", UserEmail: "[email protected]" };
        var info = "this is muti model";
        $.ajax({
            type: "put",
            url: "/api/Values/PutModelObject",
            data: {User:user,Info:info},
            dataType: "json",
            success: function (data) {
                console.log(data);
            },
            error: function (e) {
                console.log(e);
            }
        });
    }

 HttpDelete與HttpPut是一樣的就不寫了

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章