asp.net-mvc – 在ASP.NET MVC 3中使用Ajax响应发送的自定义错误
发布时间:2020-12-16 06:29:51 所属栏目:asp.Net 来源:网络整理
导读:为什么在发生错误时会使用下面的ajax响应发送自定义错误页面? 响应 {"Errors":["An error has occurred and we have been notified. We are sorry for the inconvenience."]}!DOCTYPE htmlhtmlhead meta charset="utf-8" / titleError/title Web.Config中 c
为什么在发生错误时会使用下面的ajax响应发送自定义错误页面?
响应 {"Errors":["An error has occurred and we have been notified. We are sorry for the inconvenience."]}<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>Error</title> Web.Config中 <customErrors defaultRedirect="Error" mode="On"></customErrors> BaseController.cs public class BaseController : Controller { protected override void OnException(ExceptionContext filterContext) { if (filterContext.HttpContext.Request.IsAjaxRequest()) { var response = filterContext.HttpContext.Response; var validatorModel = new ValidatorModel(); if (filterContext.Exception is AriesException && !((AriesException)filterContext.Exception).Visible && filterContext.HttpContext.IsCustomErrorEnabled) { validatorModel.Errors.Add(this.Resource("UnknownError")); } else { validatorModel.Errors.Add(filterContext.Exception.Message); } response.Clear(); response.StatusCode = (int)System.Net.HttpStatusCode.InternalServerError; response.Write(validatorModel.ToJson()); response.ContentType = "application/json"; response.TrySkipIisCustomErrors = true; filterContext.ExceptionHandled = true; System.Web.HttpContext.Current.ApplicationInstance.CompleteRequest(); } else if (filterContext.HttpContext.IsCustomErrorEnabled) { filterContext.ExceptionHandled = true; } if(filterContext.ExceptionHandled) { SiteLogger.Write(filterContext.Exception); } } } 解决方法
如果有人还有这个问题,我发现了一个稍微清洁的解决方案:
if (!filterContext.HttpContext.Request.IsAjaxRequest()) { //non-ajax exception handling code here } else { filterContext.Result = new HttpStatusCodeResult(500); filterContext.ExceptionHandled = true; } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
推荐文章
站长推荐
- 将ASP.net MVC网站部署到Azure网站的子文件夹中?
- asp.net-mvc – 限制匿名访问ASP.Net MVC站点的问
- views – 我应该在asp.net MVC6中为我的所有图像
- ASP.NET Web Forms 4.5模型绑定,其中模型包含一个
- 如何使用ASP.NET Identity 3.0没有Entity Framew
- 你如何获得asp.net控件的自动生成的name属性?
- asp.net-mvc-4 – 后退点击刷新页面 – MVC 4
- Asp.NET Core2.0 项目实战入门视频课程_完整版
- asp.net – 何时使用Request.RegisterForDispose
- 如何使用ASP.NET C#设置html输入类型文本值?
热点阅读