ASP .NET MVC - 返回异常消息给ajax调用
创始人
2024-11-11 15:00:15
0

在ASP.NET MVC中,可以通过自定义异常过滤器来返回异常消息给Ajax调用。下面是一个示例:

  1. 创建一个自定义异常过滤器,继承自HandleErrorAttribute类并实现IExceptionFilter接口:
public class AjaxExceptionFilter : HandleErrorAttribute, IExceptionFilter
{
    public void OnException(ExceptionContext filterContext)
    {
        if (filterContext.HttpContext.Request.IsAjaxRequest())
        {
            // 返回异常消息给Ajax调用
            filterContext.Result = new JsonResult
            {
                Data = new { error = filterContext.Exception.Message },
                JsonRequestBehavior = JsonRequestBehavior.AllowGet
            };
            filterContext.ExceptionHandled = true;
        }
        else
        {
            base.OnException(filterContext);
        }
    }
}
  1. 在Global.asax.cs文件中注册自定义异常过滤器:
public class MvcApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        // 注册自定义异常过滤器
        GlobalFilters.Filters.Add(new AjaxExceptionFilter());
        // 其他初始化代码...
    }
}

现在,当发生异常时,如果该请求是一个Ajax请求,将会返回一个包含异常消息的JSON对象。

相关内容

热门资讯

透视存在!hhpoker德州牛... 透视存在!hhpoker德州牛仔视频(透视)陕西辅助器具适用平台(切实是真的辅助下载)-哔哩哔哩1、...
最终!wepoker透视有没有... 最终!wepoker透视有没有(透视)凑一桌游戏关春天辅助(一直是真的辅助工具)-哔哩哔哩1、下载好...
截至目前!wepoker提高好... 截至目前!wepoker提高好牌率(透视)欢聚水鱼脚本(真是是有辅助下载)-哔哩哔哩1、欢聚水鱼脚本...
据通报!hhpoker有没有辅... 据通报!hhpoker有没有辅助(透视)凑一桌关春天辅助器在哪买(其实是有辅助修改器)-哔哩哔哩1、...
一直以来!hhpoker透视工... 一直以来!hhpoker透视工具(透视)浙江宝宝游戏辅助器(总是有辅助app)-哔哩哔哩1、浙江宝宝...
受玩家影响!aapoker插件... 受玩家影响!aapoker插件(透视)途游四川小程序有挂吗(确实是有辅助工具)-哔哩哔哩1、全新机制...
据通报!智星菠萝透视(透视)打... 据通报!智星菠萝透视(透视)打两圈泰兴辅助(真是有辅助app)-哔哩哔哩暗藏猫腻,小编详细说明打两圈...
一直以来!wepokerh5破... 一直以来!wepokerh5破解(透视)雀神麻雀科技公司(总是存在有辅助辅助器)-哔哩哔哩1、一直以...
记者获悉!拱趴大菠萝怎么开挂(... 记者获悉!拱趴大菠萝怎么开挂(透视)苹果广东雀神破解器(其实是有辅助软件)-哔哩哔哩1、许多玩家不知...
有了最新消息!wepoker软... 有了最新消息!wepoker软件辅助程序(透视)点我达辅助(竟然是有辅助软件)-哔哩哔哩1)点我达辅...