500错误之谜仅在服务器上发生

时间:2015-11-18 00:34:34

标签: jquery asp.net-mvc asp.net-web-api error-handling

我在本地从.net MVC应用程序获取请求的数据没有问题,但在服务器上ajax jquery调用报告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中

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)

1 个答案:

答案 0 :(得分:1)

这有多种原因,从缺少依赖项到错误的服务器设置。因此,我建议您设置一些正确的错误记录,您很快就会从这些日志中看到错误是什么。

在ASP.net中执行此操作的更简单方法是安装Elmah。通过nuget这样做。

此处需要注意的另一点是,默认情况下,在web api中,您不会将所有错误都记录为described here。为了确保捕获所有异常,请添加以下代码并在启动时在方法寄存器中的WebAppConfig类中通过添加config.Filters.Add(new RestfulModelStateFilterAttribute());

注册它

下面的替代方法是添加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));
    }
}