gpt4 book ai didi

asp.net-mvc - MVC中响应重定向后如何保持Server.GetLastError

转载 作者:行者123 更新时间:2023-12-03 18:23:06 25 4
gpt4 key购买 nike

在我的 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()一片空白。我如何保留它或将它传递给 Response.Redirect(String.Format("~/ControllerName/MethodName?errorType={0}"所以我可以在我的方法体中将异常作为一个对象?

最佳答案

我想建议您不是 出现错误时重定向,以便保留 URL 并设置正确的 HTTP 状态代码。

相反,在 Application_Error 中执行您的 Controller

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-mvc - MVC中响应重定向后如何保持Server.GetLastError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21113688/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com