我正在使用自動生成的默認Web Api控制器。我正在測試客戶端的驗證和錯誤處理。但不知何故,我已經意識到,詳細錯誤消息不會傳遞給客戶端。要麼我拋出HttpResponseException或返回IHttpActionResult在這兩種情況下客戶端只看到「錯誤的請求」,而不是詳細的消息。任何人都可以解釋發生了什麼問題嗎?爲什麼詳細的錯誤消息不會傳遞給HttpClient?
public IHttpActionResult Delete(int id)
{
if (id <= 0)
{
var response = new HttpResponseMessage(HttpStatusCode.NotFound)
{
Content = new StringContent("Id should be greater than zero.", System.Text.Encoding.UTF8, "text/plain"),
StatusCode = HttpStatusCode.NotFound
};
throw new HttpResponseException(response) // Either this way
}
var itemToDelete = (from i in Values
where i.Id == id
select i).SingleOrDefault();
if (itemToDelete == null)
{
return BadRequest(string.Format("Unable to find a value for the Id {0}", id)); // Or This way
}
Values.Remove(itemToDelete);
return Ok();
}
客戶端代碼爲:上述工程的
private async static Task DeleteValue(int id)
{
var url = "http://localhost:13628/api/Values/" + id;
using (var client = new HttpClient())
{
var response = await client.DeleteAsync(url);
if (response.IsSuccessStatusCode)
{
await ReadValues();
}
else
{
Console.WriteLine(response.ReasonPhrase);
Console.WriteLine(response.StatusCode);
}
}
}
無??
Thx
你在'response'中收到了一條消息嗎? –
*通常*,暴露您的Web服務器的內部工作對良性用戶沒有任何用處,但可能會將惡意暴露給惡意用戶。因此,*默認*傾向於隱藏詳細信息。 –