mvc ajax错误500,C# MVC 全局错误Application_Error中处理(包括Ajax请求)

该博客讨论了在ASP.NET MVC应用中如何在Global.asax的Application_Error事件中捕获并处理全局错误。当请求对象未创建或错误发生在非Ajax请求时,博客提供了两种不同的错误处理方案。对于Ajax请求,它返回JSON错误信息;而对于非Ajax请求,可以选择重定向到错误页面或传递错误对象到自定义错误页面。此外,还提到了配置Web.config以指定默认错误页面。
摘要由CSDN通过智能技术生成

在mvc的global.asax application_error 中处理全局错误。

如果在未到创建请求对象时报错,此时 context.handler == null 。

判断为ajax请求时,我们返回json对象字符串。不是ajax请求时,转到错误显示页面。

///

/// 全局错误

///

///

///

protected void application_error(object sender, eventargs e)

{

exception ex = server.getlasterror();

loghelper.error(ex); // 记录错误日志(nlog 挺好用的(* ̄︶ ̄))

if (context.handler == null)

{

return;

}

if (new httprequestwrapper(request).isajaxrequest())

{

response.clear();

response.contenttype = "application/json; charset=utf-8";

response.write("{\"state\":\"0\",\"msg\":\"" + ex.message + "\"}");

response.flush();

response.end();

}

else

{

// 方案一 重定向到错误页面,带上简单的错误信息

//string errurl = "/error/error?msg=" + ex.message;

//response.redirect(errurl, true);

// 方案二 带上错误对象,转到错误页

response.clear();

routedata routedata = new routedata();

routedata.values.add("controller", "error"); // 已有的错误控制器

routedata.values.add("action", "error"); // 自定义的错误页面

server.clearerror();

errorcontroller controller = new errorcontroller();

handleerrorinfo handleerrorinfo = new handleerrorinfo(ex, "error", "error");

controller.viewdata.model = handleerrorinfo;

((icontroller)controller).execute(new requestcontext(new httpcontextwrapper(((mvcapplication)sender).context), routedata));

}

}

其中方案二的对象用法,与默认的错误页(即 /shared/error.cshtml)一样。当我们不对错误进行任何处理时,在web.config中可配置错误页到 /shared/error.cshtml。

error.cshtml的代码:

@model system.web.mvc.handleerrorinfo

@{

viewbag.title = "系统错误";

layout = "~/views/shared/_layout.cshtml";

}

系统错误

@if (model != null)

{

@(model.exception.message)

}

else

{

处理请求时出错。

}

方案二的action的代码:

public actionresult error()

{

return view();

}

相关配置影响:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值