【发布时间】:2015-09-29 22:56:19
【问题描述】:
我检查了大量的帖子/教程/视频,但在一种特定情况下仍然无法使用 DELETE 方法获得工作代码:当我尝试按 ID 删除时。
下面的工作示例。我将整个 json 字符串传递给 DELETE 方法,它运行良好(基于它我敢建议 wcf/客户端配置文件中没有错误)。
WCF
[OperationContract]
[WebInvoke(Method = "DELETE",
ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json,
UriTemplate = "delete"
)]
bool DeleteNews(News news);
客户:
const string WEBSERVICE_URL = "http://localhost:33873/NewsService.svc/delete";
string jsonData = "{my json string}";
try
{
var webRequest = WebRequest.Create(WEBSERVICE_URL);
if (webRequest != null)
{
webRequest.Method = "DELETE";
webRequest.Timeout = 20000;
webRequest.ContentType = "application/json";
using (Stream s = webRequest.GetRequestStream())
{
using (StreamWriter sw = new StreamWriter(s))
sw.Write(jsonData);
}
using (Stream s = webRequest.GetResponse().GetResponseStream())
{
}
}
}
现在想演示以下对我不起作用的代码。我想知道我不能按 ID 使用 DELETE。
WCF
[OperationContract]
[WebInvoke(Method = "DELETE",
UriTemplate = "delete/?id={id}"
)]
bool DeleteNews(int id);
将 URL 放入浏览器,如 http://localhost:33873/NewsService.svc/delete/?id=10 并得到“远程服务器返回错误请求,代码为 400”(意味着客户端或我的请求有问题)。 我也尝试过如下字符串参数:
[OperationContract]
[WebInvoke(Method = "DELETE",
UriTemplate = "delete/{id}"
)]
bool DeleteNews(string id);
经过这样的转换,URL 看起来像http://localhost:33873/NewsService.svc/delete/10
结果也不成功,同样的错误。
【问题讨论】:
-
“将 URL 放入浏览器”实际上是 GET 请求。您确定要使用 DELETE 方法发送请求吗?