Skip to main content
 首页 » 编程设计

c#之asp.net mvc Response.Redirect 在 global.asax 中不起作用

2024年02月06日21kevingrace

当应用程序发生任何异常时,我试图重定向到 asp.net mvc5 的 global.asax 文件中的错误页面。执行 Response.Redirect 行后没有任何反应。

它根本没有重定向到路径 ~\View\Shared\Error.cshtml 中可用的错误页面

protected void Application_Error(object sender, EventArgs e) 
{    
    Server.ClearError(); 
    Response.Clear();       
    HttpContext.Current.Response.Redirect("~\View\Shared\Error.cshtml");     
   //return;                
} 

在网络配置中,

<system.web> 
    <customErrors mode="On" defaultRedirect="~\View\Shared\Error.cshtml" /> 
</system.web> 

我不确定出了什么问题。

我的错误 Controller :

public class ErrorController : Controller 
    { 
        // GET: Error 
        public ActionResult Error() 
        { 
            return View("Error"); 
        } 
 
    } 

请您参考如下方法:

我不建议使用 Global.asax,除非您正在进行一些自定义逻辑。我建议使用 web.config。请注意,由于 MVC 使用路由而不是物理文件,因此您应该在 web.config 中使用类似这样的内容:

<httpErrors errorMode="Custom"> <remove statusCode="404"/> <error statusCode="404" path="/error/404" responseMode="ExecuteUrl"/> <httpErrors>

但是如果你想调用一些物理文件(例如 html),你应该以这种方式使用它:

<httpErrors errorMode="Custom"> <remove statusCode="404"/> <error statusCode="404" path="/erro404.html" responseMode="File"/> <httpErrors>

现在,回到自定义逻辑。如果你真的需要使用 Global.asax,我建议你使用这样的东西:

protected void Application_Error(object sender, EventArgs e) 
{ 
    Exception exception = Server.GetLastError(); 
    Response.Clear(); 
 
    HttpException httpException = exception as HttpException; 
 
    RouteData routeData = new RouteData(); 
    routeData.Values.Add("controller", "Error"); 
 
    if (httpException == null) 
    { 
        routeData.Values.Add("action", "Index"); 
    } 
    else //It's an Http Exception, Let's handle it. 
    { 
        switch (httpException.GetHttpCode()) 
        { 
            case 404: 
                // Page not found. 
                routeData.Values.Add("action", "HttpError404"); 
                break; 
            case 500: 
                // Server error. 
                routeData.Values.Add("action", "HttpError500"); 
                break; 
 
            // Here you can handle Views to other error codes. 
            // I choose a General error template   
            default: 
                routeData.Values.Add("action", "General"); 
                break; 
        } 
    } 
 
    // Pass exception details to the target error View. 
    routeData.Values.Add("error", exception); 
 
    // Clear the error on server. 
    Server.ClearError(); 
 
    // Avoid IIS7 getting in the middle 
    Response.TrySkipIisCustomErrors = true; 
 
    // Call target Controller and pass the routeData. 
    IController errorController = new ErrorController(); 
    errorController.Execute(new RequestContext( 
            new HttpContextWrapper(Context), routeData)); 
}