WebApi的调用-1.前端调用

前端调用

WebApi的调用-1.前端调用_第1张图片
前端

html

js


后台

public class ValuesController : ApiController
    {
        [HttpGet]
        public IEnumerable GetList()
        {
            return new string[] { "value1", "value2" };
        }

        [HttpGet]
        public string Get(int id)
        {
            return "value";
        }

        [HttpGet]
        public IEnumerable GetList(int id, string pass)
        {
            return new string[] { id.ToString(), pass.ToString() };
        }

        //Get传参:实体,必须添加 FromUri
        [HttpGet]
        public string GetUserList([FromUri]User user)
        {
            return string.Format("id:{0},name:{1},pass:{2}", user.id.ToString(), user.name, user.pass);
        }

        [HttpGet]
        public string UserJsonList(string userJson)
        {
            User user = JsonConvert.DeserializeObject(userJson);
            return string.Format("id:{0},name:{1},pass:{2}", user.id.ToString(), user.name, user.pass);
        }

        // POST api/values
        [HttpPost]
        public string PostOne([FromBody]string value)
        {
            return value;
        }

        //一个表单(一个json)
        [HttpPost]
        public string PostOneForm(dynamic value)
        {
            string user = Convert.ToString(value);
            return user;
        }

        //一个表单(一个实体)
        [HttpPost]
        public string PostTwoForm(User user)
        {
            //Dictionary objects = GetRequest();

            return string.Format("id:{0},name:{1},pass:{2}", user.id.ToString(), user.name, user.pass);
        }

        [HttpPost]
        public string PostThreeeForm(JObject jObject)
        {
            //Dictionary objects = GetRequest();
            string username = HttpContext.Current.Request.Form["User[name]"];
            dynamic json = jObject;
            JObject User = json.User;
            User user = User.ToObject();
            //Dictionary objects = GetRequest();

            return string.Format("id:{0},name:{1},pass:{2}", user.id.ToString(), user.name, user.pass);
        }

        // PUT api/values/5
        public void Put(int id, [FromBody]string value)
        {
        }

        // DELETE api/values/5
        public void Delete(int id)
        {
        }

        /// 
        /// 获取所有参数   
        /// 
        /// 
        ///     A System.Collections.Generic.Dictionary value...
        /// 
        public Dictionary GetRequest()
        {
            var getrequest = HttpContext.Current.Request.Form;
            Dictionary dict = new Dictionary();

            for (int i = 0; i < getrequest.AllKeys.Length; i++)
            {
                dict.Add(getrequest.GetKey(i), getrequest[i]);
            }
            return dict;
        }
    }

你可能感兴趣的:(WebApi的调用-1.前端调用)