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

在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();

}

相关配置影响:

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值