从客户端应用程序调用wcf restful服务的DELETE方法

时间:2012-01-12 12:34:34

标签: wcf client

以下是我尝试从WCF服务调用DELETE方法的方法:

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();

但我收到400错误。

这是wcf中方法的名称:

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

我在哪里犯了错误?

1 个答案:

答案 0 :(得分:0)

尝试在服务上启用Tracing并检查跟踪日志中是否存在实际错误。您的网址也应该是

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

而不是

“HTTP://本地主机:1234 / MyService.svc /端点/的MyMethod”

更新:

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;
        }

现在替换以下行

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

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