Passing body content when calling a Delete Web API method using System.Net.Http

前端 未结 3 1609
刺人心
刺人心 2020-12-20 16:36

I have a scenario where I need to call my Web API Delete method constructed like the following:

// DELETE: api/products/{id}/headers
[HttpDelete(\"{id}/heade         


        
3条回答
  •  旧巷少年郎
    2020-12-20 17:03

    My API as below:

    // DELETE api/values
    public void Delete([FromBody]string value)
    {
    }
    

    Calling from C# server side

                string URL = "http://localhost:xxxxx/api/values";
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);
                request.Method = "DELETE";
                request.ContentType = "application/json";
                string data = Newtonsoft.Json.JsonConvert.SerializeObject("your body parameter value");
                request.ContentLength = data.Length;
                StreamWriter requestWriter = new StreamWriter(request.GetRequestStream(), System.Text.Encoding.ASCII);
                requestWriter.Write(data);
                requestWriter.Close();
    
                try
                {
                    WebResponse webResponse = request.GetResponse();
                    Stream webStream = webResponse.GetResponseStream();
                    StreamReader responseReader = new StreamReader(webStream);
                    string response = responseReader.ReadToEnd();
    
                    responseReader.Close();
                }
                catch
                {
    
                }
    

提交回复
热议问题