简体   繁体   English

ASP.NET MVC 5-错误处理-404页面未找到

[英]ASP.NET MVC 5 - Error Handle for - 404 Page not found

For standard errors I use solution error handle (see code below), and also I tried THIS (without effect) 对于标准错误,我使用解决方案错误句柄(请参见下面的代码),并且我尝试了THIS (无效)

Global.asax.cs Global.asax.cs

 protected void Application_Error(object sender, EventArgs e)
 {
        var exception = Server.GetLastError();

        var httpException = exception as HttpException;
        var 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);

        var request = Request;
        // Pass request details to the target request View.
        routeData.Values.Add("request", request);

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

ErrorController 错误控制器

public class ErrorController : Controller
{
    private readonly ILog _log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

    // GET: Error
    public ActionResult Index()
    {
        return View();
    }

    public ActionResult HttpError404(string error, HttpRequest request)
    {
        ViewBag.Title = "Page not found (Error 404)";
        ViewBag.Description = error;
        return View("~/Views/Shared/Error.cshtml");
    }

    public ActionResult HttpError500(string error, HttpRequest request)
    {
        ViewBag.Title = "Internal server error (Error 500)";
        ViewBag.Description = error;
        return View("~/Views/Shared/Error.cshtml");
    }

    public ActionResult General(string error, HttpRequest request)
    {
        ViewBag.Title = "Internal server error";

        ViewBag.Description = error;
        return View("~/Views/Shared/Error.cshtml");
    }
}

Error.cshtml Error.cshtml

@{
    Layout = "_Layout.cshtml";
}

<div class="row">
    <div class="exceptionmessage col-md-12 text-center">
        <div class="center-block">
            <img src="~/Content/i/404.png" class="img-responsive"/>
        </div>

        <strong>@ViewBag.Message</strong>
        <span class="center-block small text-uppercase">@ViewBag.Main</span>


        <div class="center-block">@Html.ActionLink("Return to the Homepage", "Index", "Home", null, new {@class = "btn btn-primary"})</div>
    </div>
</div>

I have a directory Techs where I have some XML files (for load data, something like local DB), and with this script in web.config I disable access to this folder and to download files from this folder (or when I write nonexist URL or file-like www.test.com/afsdfgsdfg.pdf ), I got IIS message 404 Page not found without redirection to my custom error 404 page from error handler code below. 我有一个Techs目录,其中有一些XML文件(用于加载数据,例如本地DB),并且在web.config使用此脚本,因此无法访问该文件夹并从该文件夹下载文件(或者当我编写不存在的URL时)或类似文件的www.test.com/afsdfgsdfg.pdf ),则没有找到IIS消息404页面,而没有从下面的错误处理程序代码重定向到我的自定义错误404页面。

错误页面

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

  <system.webServer>    
    <security xdt:Transform="Replace">
      <requestFiltering>
        <hiddenSegments>
          <add segment="Techs" />
        </hiddenSegments>
      </requestFiltering>
    </security>
  </system.webServer>

Is there any way how handle all errors with 404 page not found (with same page and not two different)? 有什么办法可以处理未找到404页的所有错误(具有同一页而不是两个不同的页)?

Thank you 谢谢

EDIT: 编辑:

I add a new route for my ErrorController into RouteConfig.cs : 我将我的ErrorController的新路由添加到RouteConfig.cs

routes.MapRoute("Error",
                "{controller}/{action}/",
                new { controller = "Error", action = "HttpError404" });

after that I change web.config to: 之后,我将web.config更改为:

<customErrors mode="On" defaultRedirect="~/Error/General">
    <error redirect="~/Error/HttpError404" statusCode="404" />
    <error redirect="~/Error/HttpError500" statusCode="500" />
</customErrors>

<httpErrors errorMode="Custom" existingResponse="Replace">
      <remove statusCode="404" />
      <error
        statusCode="404"
        path="/Error/HttpError404"
        responseMode="ExecuteURL"/>
    </httpErrors>

But it still does not work, I got HTTP Error 404.0 - Not Found or HTTP Error 403.14 - Forbidden and similar messages, when I write for example: 但是它仍然无法正常工作,例如在我编写以下消息时,出现HTTP错误404.0-找不到HTTP错误403.14-禁止和类似消息:

  • web.com/Techs/ web.com/Techs/
  • web.com/Techs/catalog.csv web.com/Techs/catalog.csv
  • web.com/Techs.pdf -> redirect to the 404 page web.com/Techs.pdf->重定向到404页面
  • web.com/Home/c.pdf web.com/Home/c.pdf

My solution that WORKS 我的解决方案

I do not add any new route to RouteConfig.cs, only edit file below. 我没有向RouteConfig.cs添加任何新路由,仅在下面编辑文件。 Controllers which I call method without a parameter, I have been treated differently. 我调用不带参数的方法的控制器,我得到了不同的对待。 Global.asax.cs and ErrorController use same as above. Global.asax.cs和ErrorController的用法与上面相同。

Web.config Web.config

<system.web>   
    <customErrors mode="On" defaultRedirect="~/Error/General">
      <error redirect="~/Error/HttpError404" statusCode="403" />
      <error redirect="~/Error/HttpError404" statusCode="404" />
      <error redirect="~/Error/HttpError500" statusCode="500" />
    </customErrors>

  </system.web>

  <system.webServer>
    <httpErrors errorMode="Custom" existingResponse="Replace">
      <remove statusCode="403" />
      <remove statusCode="404" />
      <remove statusCode="500" />
      <error
        statusCode="403"
        path="/Error/HttpError404"
        responseMode="ExecuteURL" />
      <error
        statusCode="404"
        path="/Error/HttpError404"
        responseMode="ExecuteURL" />
      <error
        statusCode="500"
        path="/Error/HttpError500"
        responseMode="ExecuteURL" />
    </httpErrors>
  </system.webServer>

In web.config add this line web.config中添加此行

<system.web>
    <customErrors mode="On" defaultRedirect="~/ErrorHandler/Index">
        <error statusCode="404" redirect="~/ErrorHandler/NotFound"/>
    </customErrors>
<system.web/>

edit: That should cover all errors with that code...but I see that you already have that. 编辑:那应该涵盖该代码的所有错误...但我看到您已经拥有了。

You can create a folder named like Error in the home directory, then create a html error page there with your own design. 您可以在主目录中创建一个名为Error的文件夹,然后使用自己的设计在其中创建html错误页面。

In your web config, add this: 在您的网络配置中,添加以下内容:

<customErrors mode="RemoteOnly" redirectMode="ResponseRewrite">
  <error statusCode="404" redirect="/Error/404.html" />
</customErrors>

This would redirect to that 404.html in the Error folder. 这将重定向到Error文件夹中的404.html

If you want to check for specific errors in the controller and redirect to the related error pages, you can create an ErrorController in the controller and the views for the different types of errors you want to check for in the Error views folder. 如果要检查控制器中的特定错误并重定向到相关的错误页面,则可以在控制器中创建一个ErrorController ,并在“ 错误视图”文件夹中创建要检查的不同类型错误的视图。 eg: 例如:

    //In the ErrorController
    // GET: /Error/404 Bad request
    public ActionResult E404()
    {
        return View();
    }

and in the controller if page is not found or id == null you can do something like: 在控制器中,如果找不到页面或id == null,则可以执行以下操作:

if (id == null)
{
    return RedirectToAction("E404", "Error");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM