Restful Web Api Get 和 Post 请求的参数设置

时间:2022-10-14 12:02:12

1、Get请求(用HttpClient或HttpWebRequest)

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

static void Main(string[] args)
{
string url = "http://localhost:46090/api/Ticket/3";//直接在url后面带上参数
 HttpClient client = new HttpClient();
            HttpResponseMessage message = client.GetAsync(url).Result;
            string result =message.Content.ReadAsStringAsync().Result;//3
 }

2、Post 请求:

[API的post方法的参数里面必须添加[FromBody]特性,并且只能有一个参数,要传递多个参数的时候把参数封装成一个类来传递:

       [HttpPost]
public IHttpActionResult Post([FromBody]string last)
{
Person p = new Controllers.Person() { LastName = last, FirstName = "Longxi" };
return Json(p);
}
  static void Main(string[] args)        {            string url = "http://localhost:46090/api/Ticket";            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);            request.Method = "Post";            request.ContentType = "application/json";            //string strContent = "lastName=2&firstName=444&middleName=5555";            string strContent = @"tytt";//只传递一个参数时候,不需要参数名,直接对该值进行json序列化就行            strContent = JsonConvert.SerializeObject (strContent);            byte[] buffer = Encoding.UTF8.GetBytes(strContent);            request.ContentLength = buffer.Length;            using (Stream dataStream = request.GetRequestStream())            {                dataStream.Write(buffer, 0, buffer.Length);            }            HttpWebResponse response = (HttpWebResponse)request.GetResponse();            using (StreamReader dataStream = new StreamReader(response.GetResponseStream()))            {                var result = dataStream.ReadToEnd();                Person p = JsonConvert.DeserializeObject<Person>(result);                Console.WriteLine(p.FirstName+" "+p.LastName);            }}

   [HttpPost]
        public IHttpActionResult Post([FromBody]Person person)
        {
            return Json(person);
        }

static void Main(string[] args)
{
string url = "http://localhost:46090/api/Ticket";

//HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
//request.Method = "Post";
//request.ContentType = "application/json";
////string strContent = "lastName=2&firstName=444&middleName=5555";
////string strContent = @"tytt";
////strContent = JsonConvert.SerializeObject (strContent);
//var requestJson = JsonConvert.SerializeObject(new { LastName = "354353",FirstName="Longxi"});
//byte[] buffer = Encoding.UTF8.GetBytes(requestJson);
//request.ContentLength = buffer.Length;
//using (Stream dataStream = request.GetRequestStream())
//{

// dataStream.Write(buffer, 0, buffer.Length);

//}
//HttpWebResponse response = (HttpWebResponse)request.GetResponse();
//using (StreamReader dataStream = new StreamReader(response.GetResponseStream()))
//{
// var result = dataStream.ReadToEnd();
// Person p = JsonConvert.DeserializeObject<Person>(result);
// Console.WriteLine(p.FirstName+" "+p.LastName);
//}

Uri serviceReq = new Uri(url);
HttpClient client = new HttpClient();
//string strContent = @"{""lastName"":""2"",""firstName"":""444"",""middleName"":""5555""}";
var requestJson = JsonConvert.SerializeObject(new { LastName = "354353", FirstName = "bbb" });
HttpContent content = new StringContent(requestJson);//(@"{ ""lastName"":""2"",""firstName"":""444"",""middleName"":""5555""}");
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");

// Send a request asynchronously continue when complete
client.PostAsync(serviceReq, content).ContinueWith(
(requestTask) =>
{
// Get HTTP response from completed task.
HttpResponseMessage response = requestTask.Result;

// Check that response was successful or throw exception
response.EnsureSuccessStatusCode();

// Read response asynchronously as JsonValue and write out top facts for each country
response.Content.ReadAsStringAsync().ContinueWith(
(readTask) =>
{
Person p = JsonConvert.DeserializeObject<Person>(readTask.Result);
Console.WriteLine(p.FirstName+" "+p.LastName);

});
});
Console.ReadKey();
}