Restful Web Api Get 과 Post 에서 요청 한 인자 설정

5431 단어 ASP.NETMVC
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(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(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(readTask.Result);
                            Console.WriteLine(p.FirstName+" "+p.LastName);

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

좋은 웹페이지 즐겨찾기