aspnet mvc有HandleError过滤器,如果发生错误将返回视图,但如果在调用JsonResult时发生错误,Action如何返回表示错误的JSON对象?
我不想在每个在try/catch中返回JsonResult的动作方法中包装代码来完成它,我宁愿通过添加'HandleJsonError'属性或使用现有的HandleError属性来执行它所需的操作方法.
Haa*_*ked 10
看一下HandleErrorAttribute的MVC实现.它返回一个ViewResult.您可以编写自己的版本(HandleJsonErrorAttribute)来返回JsonResult.
简而言之,要走的路可以是扩展HandleErrorAttribute,如下所示:
public class OncHandleErrorAttribute : HandleErrorAttribute
{
public override void OnException(ExceptionContext context)
{
// Elmah-Log only handled exceptions
if (context.ExceptionHandled)
ErrorSignal.FromCurrentContext().Raise(context.Exception);
if (context.HttpContext.Request.IsAjaxRequest())
{
// if request was an Ajax request, respond with json with Error field
var jsonResult = new ErrorController { ControllerContext = context }.GetJsonError(context.Exception);
jsonResult.ExecuteResult(context);
context.ExceptionHandled = true;
}
else
{
// if not an ajax request, continue with logic implemented by MVC -> html error page
base.OnException(context);
}
}
}
Run Code Online (Sandbox Code Playgroud)
如果您不需要,请删除Elmah日志记录代码行.我使用我的一个控制器根据错误和上下文返回一个json.这是样本:
public class ErrorController : Controller
{
public ActionResult GetJsonError(Exception ex)
{
var ticketId = Guid.NewGuid(); // Lets issue a ticket to show the user and have in the log
Request.ServerVariables["TTicketID"] = ticketId.ToString(); // Elmah will show this in a nice table
ErrorSignal.FromCurrentContext().Raise(ex); //ELMAH Signaling
ex.Data.Add("TTicketID", ticketId.ToString()); // Trying to see where this one gets in Elmah
return Json(new { Error = String.Format("Support ticket: {0}\r\n Error: {1}", ticketId, ex.ToString()) }, JsonRequestBehavior.AllowGet);
}
Run Code Online (Sandbox Code Playgroud)
我在上面添加了一些票证信息,你可以忽略它.由于实现了过滤器的方式(扩展了默认的HandleErrorAttributes),我们可以从全局过滤器中删除HandleErrorAttribute:
public class MvcApplication : System.Web.HttpApplication
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new GlobalAuthorise());
filters.Add(new OncHandleErrorAttribute());
//filters.Add(new HandleErrorAttribute());
}
Run Code Online (Sandbox Code Playgroud)
基本上就是这样.您可以阅读我的博客条目以获取更多详细信息,但是对于这个想法,上面应该足够了.
| 归档时间: |
|
| 查看次数: |
3668 次 |
| 最近记录: |