我正在用asp.net mvc構建一個REST風格的web api,它會返回純json數據。在我的客戶端,我使用backbone.js與之通信。ASP.NET MVC HttpException消息未在客戶端上顯示
我的問題是,我如何捕捉JavaScript中的消息?例如。如果用戶沒有權限刪除或沒有與該ID匹配的項目,該怎麼辦?我被告知拋出http錯誤而不是自定義json。 所以我的代碼是:
[HttpDelete]
public ActionResult Index(int id)
{
if (id == 1)
{
throw new HttpException(404, "No user with that ID");
}
else if (id == 2)
{
throw new HttpException(401, "You have no authorization to delete this user");
}
return Json(true);
}
如何我在JavaScript回調訪問的消息?回調將如下所示:
function (model, response) {
alert("failed");
//response.responseText would contain the html you would see for asp.net
}
我沒有看到消息,我從服務器返回的數據中發現任何異常情況。
嗨,我如何訪問一個特定的字符串,如:''沒有該用戶名的用戶''',這是拋出錯誤時通過? 'errorThrown'中的數據是完整的錯誤html頁面。 –
@Lol編碼器,如果你想訪問字符串和東西,你應該返回JSON對象,而不是拋出任何異常。您應該選擇您想要的兩種:完全RESTFul API,其中狀態碼足以讓您暗示錯誤消息或返回JSON對象。 –