c# - MVC OnException 返回 Json 结果以显示错误消息

标签 c# asp.net-mvc error-handling

当发生错误时,我的 OnException() 会被触发,并且错误会从我的 ajax 调用中正确记录。

问题是我在 Json 结果中返回的错误消息未显示,并且 result.data 为“”。

你能看出我的代码做错了什么吗?

        $.post("/Admin/CreateOrganization", createOrganizationModel)
        .done(function (data) {
            if (data.success) {                       
                //Everything is good 
            }
            else {
                swal(
                    'Failed to create organization.',
                    data.errorMessage,
                    'error'
                );
            }
        })
        .fail(function () {
            swal(
                'Failed to create organization. Please reload and try again',
                '',
                'error'
            );
        });

这是我的 OnException:

        protected override void OnException(ExceptionContext filterContext)
    {
        // Log to database...

        if (filterContext.HttpContext.Request.IsAjaxRequest())
        {
            filterContext.ExceptionHandled = true;
            filterContext.Result = new JsonResult
            {
                Data = new { success = false, errorMessage = "An error has occurred." },
                JsonRequestBehavior = JsonRequestBehavior.AllowGet
            };

            base.OnException(filterContext);
        }
        else
        {
            Server.ClearError();

            RedirectToErrorView();
        }
    }

最佳答案

答案:

我在发布这个问题时修复了它。

我的数据中有“错误”= ...而不是“errorMessage”

它现在在我的甜蜜警报消息框中显示错误消息。

关于c# - MVC OnException 返回 Json 结果以显示错误消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54947405/

相关文章:

c# - <form>中的Asp.net core设置后台

excel - 将来自不同Excel工作簿的数据收集到一个工作簿中

c# - 为什么Covariance和Contravariance这样命名?

c# - Assembly.GetCustomAttributes 仍然被认为是最佳方法吗?

.net - 强制 ActionLinks 呈现为小写

c# - 将 json 返回到核心 2 中的部分 View

php - 如何在CodeIgniter中为403禁止的错误设置自定义页面

asp.net - 全局记录来自 ASP.NET [ScriptService] 服务的异常

c# - 无法理解拳击是如何完成的

asp.net - HTTP缓存: Cache-Control