3
我有一個控制器的幾種方法,看起來像:ASP.NET MVC異常與AJAX/JSON處理
[HttpPost]
public ActionResult AddEditCommentToInvoice(string invoiceNumber, string comments)
{
var response = new { success = true, msg = "Comment saved", statusMsg = "Comment saved" };
try
{
var recordsModified = invoiceService.AddCommentsToInvoice(invoiceNumber, comments);
Log.Info(recordsModified ? "Updated Comment" : "Did not update Comment");
} catch (Exception ex) {
Response.StatusCode = (int)HttpStatusCode.InternalServerError;
return Json(new {
success = false,
msg = "There is missing field data",
statusMsg = ex.Message
}, JsonRequestBehavior.AllowGet);
}
return Json(response, JsonRequestBehavior.AllowGet);
}
儘管此代碼的工作,我不舒服的這種做法,因爲:
- 嘗試/捕撈量是昂貴
- 的代碼捕獲的System.Exception
- 該代碼是難看
現在我知道我可以使用OnException或HandleError屬性。
我也對ELMAH做了一些研究,看起來很有希望。
但我仍然想通過AJAX將JSON返回給我的用戶,以表明操作是否成功。
所以我的問題是,有沒有人使用三種方法(或特別是ELMAH)的任何一種通過AJAX返回JSON?
ELMAH只監視並報告未處理的異常,它不會修改您的應用程序流,屬性方法是您最好的選擇。 – KiwiPiet
我做同樣的事情,我一直恨它。我期待着看到一個解決方案。它一直是我'技術債務'中的項目之一。 – kryptonkal
@kryptonkal - 我剛剛遇到了這個 - http://plainoldstan.blogspot.cz/2012/08/mvc-3-elmah-handle-ajaxjson-action.html – coson