2015-11-18 18 views
1

我在本地沒有問題從.net MVC應用程序獲取請求的數據,但在服務器上,ajax jquery調用報告500錯誤。通常,我可以在本地單步執行代碼,找出可能導致服務器上出現500錯誤的「可能」。500錯誤之謎只發生在服務器上

這一次,我意識到,我真的需要一個更好的編碼策略,以捕獲錯誤,要麼登錄或將它們向我彙報

public ActionResult PhotoList(int tblGateCode_ID) 
{ 
    try 
    { 
     context = new DBGate(); 
     var images = context.tblGateCodeImages.Where(x => x.tblGateCode_ID == tblGateCode_ID); 
     foreach (var img in images) 
     { 
      img.GatePhoto = null; 
     } 
     ViewModel viewModel = new ViewModel 
     { 
      GateCodeImageList = images.ToList() 
     }; 
     return Json(viewModel, "application/json", JsonRequestBehavior.AllowGet); 

     } 
     catch (Exception e) 
     { 

     //?? 
     } 
    } 
} 

更新:

我也嘗試添加在代碼到我的捕獲

catch (Exception e) 
{ 
    return Json(e.Message, "application/json", JsonRequestBehavior.AllowGet); 
} 

要麼我不被允許這樣做...或者其他一些原因我仍然得到500?

Failed to load resource: the server responded with a status of 500 (Internal Server Error) 
+0

你可以使用你的瀏覽器工具(網絡選項卡),以檢查響應,並看到錯誤 –

+0

響應的更多細節只是不夠好,我想要做的只是傳回例外。所以我想e.Message –

+0

你有多少訪問服務器?如果您可以查看事件日誌,則可以將exception.message寫入事件日誌以幫助調試。 https://support.microsoft.com/en-us/kb/307024 –

回答

1

造成這種情況的原因有很多,從缺失依賴到錯誤的服務器設置。因此,我會建議設置一些適當的錯誤日誌記錄,您將很快從這些日誌中看到錯誤是什麼。

在ASP.net中執行此操作的更簡單的方法是安裝Elmah。通過nuget做到這一點。

此處需要注意的其他一點是,默認情況下,在web api中,您不會將所有錯誤選爲described here。爲了確保捕獲所有異常,請添加以下代碼,並通過添加config.Filters.Add(new RestfulModelStateFilterAttribute()),在啓動時將其註冊到方法寄存器的WebAppConfig類中;

到下面的替代方法是添加NuGet包Elmah.Contrib.WebApi

using System; 
using System.Net; 
using System.Net.Http; 
using System.Web; 
using System.Web.Http; 
using System.Web.Http.Controllers; 
using System.Web.Http.Filters; 
using Elmah; 
using Newtonsoft.Json; 

/// <summary> 
/// see http://sergeyakopov.com/2015/03/restful-validation-with-aspnet-web-api-and-fluentvalidation 
/// and https://github.com/rdingwall/elmah-contrib-webapi/blob/master/src/Elmah.Contrib.WebApi/ElmahHandleErrorApiAttribute.cs 
/// this is a combination of both, but with logging enabled for anything above 400, not 500 like the link above. 
/// </summary> 
public class RestfulModelStateFilterAttribute : ActionFilterAttribute 
{ 

    public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext) 
    { 
     base.OnActionExecuted(actionExecutedContext); 

     var e = actionExecutedContext.Exception; 
     if (e != null) 
     { 
      RaiseOrLog(e, actionExecutedContext); 
     } 
     else if ((int)actionExecutedContext.Response.StatusCode >= 400) 
     { 
      RaiseOrLog(
       new HttpException(
        (int)actionExecutedContext.Response.StatusCode, 
        ResolveMessage(actionExecutedContext)), 
       actionExecutedContext); 
     } 
    } 

    private string ResolveMessage(HttpActionExecutedContext actionExecutedContext) 
    { 
     const string messageKey = "Message"; 

     var defaultMessage = actionExecutedContext.Response.ReasonPhrase; 
     var objectContent = actionExecutedContext.Response.Content as ObjectContent<HttpError>; 
     if (objectContent == null) return defaultMessage; 

     var value = objectContent.Value as HttpError; 
     if (value == null) return defaultMessage; 

     if (!value.ContainsKey(messageKey)) return defaultMessage; 

     var message = value[messageKey] as string; 
     return string.IsNullOrWhiteSpace(message) ? defaultMessage : message; 
    } 

    private void RaiseOrLog(Exception exception, HttpActionExecutedContext actionExecutedContext) 
    { 
     if (RaiseErrorSignal(exception) // prefer signaling, if possible 
      || IsFiltered(actionExecutedContext)) // filtered? 
      return; 

     LogException(exception); 
    } 

    private static bool RaiseErrorSignal(Exception e) 
    { 
     var context = HttpContext.Current; 
     if (context == null) 
      return false; 
     var application = HttpContext.Current.ApplicationInstance; 
     if (application == null) 
      return false; 
     var signal = ErrorSignal.Get(application); 
     if (signal == null) 
      return false; 
     signal.Raise(e, context); 
     return true; 
    } 

    private static bool IsFiltered(HttpActionExecutedContext context) 
    { 
     var config = HttpContext.Current.GetSection("elmah/errorFilter") 
        as ErrorFilterConfiguration; 

     if (config == null) 
      return false; 

     var testContext = new ErrorFilterModule.AssertionHelperContext(
            context.Exception, HttpContext.Current); 

     return config.Assertion.Test(testContext); 
    } 

    private static void LogException(Exception e) 
    { 
     var context = HttpContext.Current; 
     Elmah.ErrorLog.GetDefault(context).Log(new Error(e, context)); 
    } 
}