2015-12-02 92 views
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); 
} 

儘管此代碼的工作,我不舒服的這種做法,因爲:

  1. 嘗試/捕撈量是昂貴
  2. 的代碼捕獲的System.Exception
  3. 該代碼是難看

現在我知道我可以使用OnException或HandleError屬性。
我也對ELMAH做了一些研究,看起來很有希望。

但我仍然想通過AJAX將JSON返回給我的用戶,以表明操作是否成功。

所以我的問題是,有沒有人使用三種方法(或特別是ELMAH)的任何一種通過AJAX返回JSON?

+0

ELMAH只監視並報告未處理的異常,它不會修改您的應用程序流,屬性方法是您最好的選擇。 – KiwiPiet

+0

我做同樣的事情,我一直恨它。我期待着看到一個解決方案。它一直是我'技術債務'中的項目之一。 – kryptonkal

+0

@kryptonkal - 我剛剛遇到了這個 - http://plainoldstan.blogspot.cz/2012/08/mvc-3-elmah-handle-ajaxjson-action.html – coson

回答

2

我使用另一種方法,這種方法可以通過GlobalFilters在控制器級別或全局應用。在我的MVC控制器,你可以覆蓋OnActionExecuted方法,並做到這一點:

protected override void OnActionExecuted(ActionExecutedContext filterContext) 
    { 
     if (filterContext.Exception != null) 
     { 
     filterContext.Result = Json(new { success = false }); 
     return; 
     } 

     base.OnActionExecuted(filterContext); 
    } 

這也可以作爲一個動作過濾器屬性來完成。在控制器中不需要任何異常處理 - 如果發生異常,則在結果的上下文中處理。