加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

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;
    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读