asp.net-mvc – 如何在响应重定向MVC后保留Server.GetLastError
发布时间:2020-12-16 07:33:14 所属栏目:asp.Net 来源:网络整理
导读:在我的Global.asax中,我定义了Application_error方法: protected void Application_Error(object sender,EventArgs e){ // Code that runs when an unhandled error occurs // Get the exception object. var exc = Server.GetLastError(); //logics Respon
在我的Global.asax中,我定义了Application_error方法:
protected void Application_Error(object sender,EventArgs e) { // Code that runs when an unhandled error occurs // Get the exception object. var exc = Server.GetLastError(); //logics Response.Redirect(String.Format("~/ControllerName/MethodName?errorType={0}",errorAsInteger)); } 并且exc变量确实保留了最后一个错误但是在响应方法(MethodName)中从响应重定向后,Server.GetLastError()为null.如何保留它或将其传递给Response.Redirect(String.Format(“?/ ControllerName / MethodName?errorType = {0}”)所以我可以在我的方法体中将异常作为对象? 解决方法
我想建议您在出现错误时不重定向,以便保留URL并设置正确的HTTP状态代码.
而是在Application_Error中执行您的控制器 protected void Application_Error(object sender,EventArgs e) { var exception = Server.GetLastError(); var httpContext = ((HttpApplication)sender).Context; httpContext.Response.Clear(); httpContext.ClearError(); ExecuteErrorController(httpContext,exception); } private void ExecuteErrorController(HttpContext httpContext,Exception exception) { var routeData = new RouteData(); routeData.Values["controller"] = "Error"; routeData.Values["action"] = "Index"; routeData.Values["errorType"] = 10; //this is your error code. Can this be retrieved from your error controller instead? routeData.Values["exception"] = exception; using (Controller controller = new ErrorController()) { ((IController)controller).Execute(new RequestContext(new HttpContextWrapper(httpContext),routeData)); } } 然后是ErrorController public class ErrorController : Controller { public ActionResult Index(Exception exception,int errorType) { Response.TrySkipIisCustomErrors = true; Response.StatusCode = GetStatusCode(exception); return View(); } private int GetStatusCode(Exception exception) { var httpException = exception as HttpException; return httpException != null ? httpException.GetHttpCode() : (int)HttpStatusCode.InternalServerError; } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- asp.net – page load()或者page init()
- asp.net-mvc – asp.net mvc3 jquery ui对话框和客户端验证
- asp.net-mvc – 保持控制器瘦(太多的动作方法)
- asp.net-mvc-2 – <::<%:和<%=与嵌套代码(表达式)
- asp.net-mvc – 使用HtmlHelper类时,MVC单选按钮列表未分组
- entity-framework-4 – 通过扩展方法的IDbSet和公开包含方法
- asp.net – 使用MvcBuildViews构建Razor = true失败
- asp.net – 处理通用http处理程序中的会话超时
- 使用Asp.NET标识进行LDAP身份验证
- asp.net-mvc – 在IIS7上设置mvc应用程序?
推荐文章
站长推荐
热点阅读