[英]WCF The Remote Server Returned an Unexpected Response: (400) Bad Request
[英]WCF and RESTful API: remote server returned bad request 400 on DELETE method
我檢查了很多帖子/教程/視頻,但在一種特定情況下仍然無法使用DELETE方法獲得工作代碼:當我嘗試通過ID進行刪除時。
下面的工作示例。 我正在將整個json字符串傳遞給DELETE方法,它可以完美運行(基於此,我敢建議wcf / client配置文件中沒有錯誤)。
世界足球聯合會
[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。
世界足球聯合會
[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
結果也未成功,並出現相同的錯誤。
您是否在IISExpress中啟用了“刪除”動詞
http://www.iis.net/learn/extensions/introduction-to-iis-express/iis-express-faq http://stevemichelotti.com/resolve-404-in-iis-express-for-put-and -刪除動詞/
您也可以使用Fiddler手動測試PUT,DELET動詞
問題已解決。 我已經嘗試了幾乎所有與此問題相關的東西。 根據錯誤代碼,我100%確認這是我發送給服務器的錯誤請求/網址。
更改配置文件中的服務器行為以查看服務器端是否有任何異常后,我發現了導致問題的原因。
<serviceBehaviors>
<behavior name="Default">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="true" />
</behavior>
</serviceBehaviors>
我將includeExceptionDetailInFaults
為true
並獲得以下詳細信息:
根據說明,由於錯誤的LINQ查詢,我的服務器無法處理請求。 我的DELETE方法的實現如下:
public bool DeleteNews(string id)
{
using (EF.ServiceDBEntities context = new EF.ServiceDBEntities())
{
var n = context.News.FirstOrDefault(x => x.NewsID == int.Parse(id));
if (n != null)
{
context.News.Remove(n);
context.SaveChanges();
return true;
}
}
return false;
}
不允許這樣的條件x => x.NewsID == int.Parse(id)
。 當我將int.Parse(id)
從查詢中移出時,問題消失了。 這里有一些細節。
即使這樣,我也無法理解為什么我的服務器返回erorr代碼400(錯誤請求)? 這個異常是由服務器產生的,不是嗎? 據我所知,代碼500屬於內部服務器錯誤,我的異常是一個很好的示例。 任何意見表示贊賞。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.