MVC 3中处理JSON请求异常,如何确保接收到的响应是完整的JSON格式?
- 内容介绍
- 文章标签
- 相关推荐
本文共计226个文字,预计阅读时间需要1分钟。
我正在寻找一种高效/智能/简洁的方式来全局处理错误,例如,如果请求是Json并且发生异常,结果应该是json而不是。寻找现有的解决方案或建立自己的信息机制。一种常见的方法是编写“‘
我正在寻找一个好的/智能/干净的方式来全局处理错误,这样如果请求是Json并且发生异常,结果应该是json而不是html.寻找现有的解决方案或如何建立自己的一些信息.
一种常见的方法是编写自定义异常过滤器:public class MyErrorHandlerAttribute : FilterAttribute, IExceptionFilter { public void OnException(ExceptionContext filterContext) { filterContext.ExceptionHandled = true; filterContext.Result = new JsonResult { Data = new { success = false, error = filterContext.Exception.ToString() }, JsonRequestBehavior = JsonRequestBehavior.AllowGet }; } }
可以在Global.asax中注册为全局过滤器.然后简单地查询一些动作:
$.getJSON('/someController/someAction', function (result) { if (!result.success) { alert(result.error); } else { // handle the success } });
本文共计226个文字,预计阅读时间需要1分钟。
我正在寻找一种高效/智能/简洁的方式来全局处理错误,例如,如果请求是Json并且发生异常,结果应该是json而不是。寻找现有的解决方案或建立自己的信息机制。一种常见的方法是编写“‘
我正在寻找一个好的/智能/干净的方式来全局处理错误,这样如果请求是Json并且发生异常,结果应该是json而不是html.寻找现有的解决方案或如何建立自己的一些信息.
一种常见的方法是编写自定义异常过滤器:public class MyErrorHandlerAttribute : FilterAttribute, IExceptionFilter { public void OnException(ExceptionContext filterContext) { filterContext.ExceptionHandled = true; filterContext.Result = new JsonResult { Data = new { success = false, error = filterContext.Exception.ToString() }, JsonRequestBehavior = JsonRequestBehavior.AllowGet }; } }
可以在Global.asax中注册为全局过滤器.然后简单地查询一些动作:
$.getJSON('/someController/someAction', function (result) { if (!result.success) { alert(result.error); } else { // handle the success } });

