在調用Web服務並將Json結果返回到視圖的asp.net mvc Web應用程序中,我有以下操作方法: -如何在Web服務關閉的情況下將錯誤消息作爲JSON對象返回
public ActionResult ListPackages()
{
using (var client = new WebClient())
{
try{
var query = HttpUtility.ParseQueryString(string.Empty);
UriBuilder("http://localhost:8080/jw/web/json/workflow/package/list");
url.Query = query.ToString();
string json = client.DownloadString(url.ToString());
Thread.Sleep(500);
return Content(json, "application/json");
}
catch (System.Net.WebException ex) {
return Content("Error, service is down. please try again later", "application/json");
}
}
}
然後在視圖我定義了以下Ajax.Actionlink: -
@Ajax.ActionLink("Get Process List", "ListPackages", "Home",
new AjaxOptions
{
HttpMethod = "GET",
LoadingElementId = "tobehide",
OnSuccess = "getpackagelist"
})
和以下getpackagelist Java腳本: -
function getpackagelist(result) {
$('#products').empty();
$('#title').text("All Processes");
$.each(result.data, function (key, val) {
var str = val.packageName;
$('<li/>', { text: str }).appendTo($('#products'));
});
$('#tobehide').hide();
}
我現在面臨的問題是,櫃面Web服務是向下,System.Net.WebException
異常發生" Error, service is down. please try again later "
maeeage不會在視圖中顯示,並沒有將AJAX加載圖像之後顯示...
: ::編輯:::
我修改劇本是因爲: -
function getpackagelist(result) {
if (result.error == null) {
$('#products').empty();
$('#title').text("All Processes");
$.each(result.data, function (key, val) {
var str = val.packageName;
$('<li/>', { text: str })
.appendTo($('#products'));
});
$('#tobehide').hide();
}
else {
$('<li/>', { text: result.error })
.appendTo($('#products'));
}
而且操作方法是如下: -
catch (System.Net.WebException) {
return new JsonResult()
{
Data = new { error = "Error, service is down. please try again later" }
};
但仍然沒有錯誤將顯示在WebException被提出。 BR
不知道是你的代碼將工作:所以,你可以使用類似顯示錯誤消息。因爲如果你正在處理一個異常,那麼on-failure將不會觸發,但是在這種情況下,Onsuccess仍然會被觸發 –
@johnG啊,你是對的。我太困了... – McGarnagle
你的新代碼將無法正常工作..我認爲你的意思是JsonResult()而不是JsonResultContent().. –