简体   繁体   中英

Call DELETE method of wcf restful service from client applicaiton

Here is how I try to call the DELETE method from my WCF service:

string tmpUrl1 = "http://localhost:1234/MyService.svc/EndPoint/MyMethod";
WebRequest request1 = WebRequest.Create(tmpUrl1);
request1.Method = "DELETE";
byte[] byteArray1 = Encoding.UTF8.GetBytes("{\"idName\":" + newIdName + "}");
request1.ContentType = "application/json";
request1.ContentLength = byteArray1.Length;
Stream dataStream1 = request1.GetRequestStream();
dataStream1.Write(byteArray1, 0, byteArray1.Length);
dataStream1.Close();
WebResponse response1 = request1.GetResponse();

But I get error 400.

Here is the method's name in the wcf:

[OperationContract]
    [WebInvoke(
        Method = "DELETE",
        RequestFormat = WebMessageFormat.Json,
        ResponseFormat = WebMessageFormat.Json,
        UriTemplate = "/MyMethod/{deleteRP}/",
        BodyStyle = WebMessageBodyStyle.Bare
                )]
    MyClass MyMethod(string deleteRP);

Where am I making a mistake?

Try enabling Tracing on your service and inspect the trace log for the actual error. Also your url address should have something like

"http://localhost:1234/MyService.svc/EndPoint/MyMethod/55" 

rather than

"http://localhost:1234/MyService.svc/EndPoint/MyMethod"

UPDATE:

private static byte[] ToByteArrayUsingDataContractSer<T>(T requestBody)
        {
            byte[] bytes = null;
            var serializer1 = new DataContractSerializer(typeof(T));
            var ms1 = new MemoryStream();
            serializer1.WriteObject(ms1, requestBody);
            ms1.Position = 0;
            var reader = new StreamReader(ms1);
            bytes = ms1.ToArray();
            return bytes;
        }

Now replace the following line

byte[] byteArray1 = Encoding.UTF8.GetBytes("{\"idName\":" + newIdName + "}"); 

with

byte[] array = ToByteArrayUsingDataContractSer<string>("{\"idName\":" + newIdName + "}"); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM