【问题标题】:Create custom error when it returns 404 in ASP.NET MVC在 ASP.NET MVC 中返回 404 时创建自定义错误
【发布时间】:2017-01-13 09:48:47
【问题描述】:

我尝试搜索并找到了一些解决方案。我试了一下,但没有运气。大多数公认的解决方案是配置您的Web.config 文件,我试过了,但它仍然返回默认错误页面

<configuration>
<system.web>
<customErrors mode="On">
  <error statusCode="404"
         redirect="~/Error/Error404" />
</customErrors>
</system.web>
</configuration>

还有其他方法可以配置吗?

我不想在 IIS 中配置它

【问题讨论】:

    标签: asp.net-mvc http-status-code-404 custom-errors


    【解决方案1】:

    此解决方案不需要更改 web.config 文件或包罗万象的路由。

    首先,像这样创建一个控制器;

    public class ErrorController : Controller
    {
    public ActionResult Index()
    {
        ViewBag.Title = "Regular Error";
        return View();
    }
    
    public ActionResult NotFound404()
    {
        ViewBag.Title = "Error 404 - File not Found";
        return View("Index");
    }
    }
    

    然后在“Views/Error/Index.cshtml”下创建视图为;

     @{
      Layout = "~/Views/Shared/_Layout.cshtml";
     }                     
    <p>We're sorry, page you're looking for is, sadly, not here.</p>
    

    然后在 Global asax 文件中添加如下内容:

    protected void Application_Error(object sender, EventArgs e)
        {
        // Do whatever you want to do with the error
    
        //Show the custom error page...
        Server.ClearError(); 
        var routeData = new RouteData();
        routeData.Values["controller"] = "Error";
    
        if ((Context.Server.GetLastError() is HttpException) && ((Context.Server.GetLastError() as HttpException).GetHttpCode() != 404))
        {
            routeData.Values["action"] = "Index";
        }
        else
        {
            // Handle 404 error and response code
            Response.StatusCode = 404;
            routeData.Values["action"] = "NotFound404";
        } 
        Response.TrySkipIisCustomErrors = true; // If you are using IIS7, have this line
        IController errorsController = new ErrorController();
        HttpContextWrapper wrapper = new HttpContextWrapper(Context);
        var rc = new System.Web.Routing.RequestContext(wrapper, routeData);
        errorsController.Execute(rc);
     }
    

    如果您在执行此操作后仍然收到自定义 IIS 错误页面,请确保在 Web 配置文件中将以下部分注释掉(或为空):

       <system.web>
        <customErrors mode="Off" />
       </system.web>
       <system.webServer>   
        <httpErrors>     
        </httpErrors>
       </system.webServer>
    

    【讨论】:

    • 嗨!我尝试了你的建议它的工作但我现在的问题是_Layout.cshtml中的代码已被放入&lt;pre&gt; &lt;/pre&gt;
    • 我使用了Response.Redirect("~/Error/Index"); 而不是您使用的routeData 及其工作。谢谢
    • @FrostyPinky 不客气,很高兴我能提供帮助:)
    猜你喜欢
    • 2011-09-24
    • 1970-01-01
    • 2011-08-03
    • 2015-10-09
    • 2014-01-30
    • 2021-02-07
    • 1970-01-01
    • 1970-01-01
    • 2010-10-07
    相关资源
    最近更新 更多