asp.net mvc web api post请求带一个参数

post请求带一个参数

<!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="https://cdn.staticfile.org/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
    <script>
        $(function () {
            var data = {};
            data.value = 'a';
            $.post("http://localhost:42875/api/values","=a", function (res) {
                alert(res);
            });
        });
    </script>
</body>
</html>

后台:

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

namespace MvcApplication1.Controllers
{
    public class ValuesController : ApiController
    {
        // GET api/values
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }

        // GET api/values/5
        public string Get(int id)
        {
            return "value";
        }

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

        // PUT api/values/5
        public string Put(int id, [FromBody]string value)
        {
            return value + id.ToString();
        }

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

    public class Obj1 {
        public string name{get;set;}
        public string tel{get;set;}
    }
}

post 请求带多个参数

<!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="https://cdn.staticfile.org/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
    <script>
        $(function () {
            var data = {};
            data.name = 'a';
            data.tel = '110';
            $.post("http://localhost:42875/api/default1", data, function (res) {
                alert(res);
            });
        });
    </script>
</body>
</html>

后台:

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

namespace MvcApplication1.Controllers
{
    public class Default1Controller : ApiController
    {
        // GET api/default1
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }

        // GET api/default1/5
        public string Get(int id)
        {
            return "value";
        }

        // POST api/default1
        public void Post([FromBody]Obj1 value)
        {
        }

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

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

猜你喜欢

转载自blog.csdn.net/qq503690160/article/details/85091400