ASP.NET Ошибка 404 в дизайне сайта с правильным кодом для робота

Делаем нормальную ошибку для отсутствующих страниц, которая не испугает пользователя, а роботу покажет корректный код без всяких редиректов.

1. Контроллер с методами для каждой ошибки. Не забудьте создать представление для каждого метода.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using System.Web.SessionState;
using System.Web.UI;

//Тут ваш namespace не забудьте

 [SessionState(SessionStateBehavior.Disabled)]
    [OutputCache(Location = OutputCacheLocation.None, NoStore = true)]
    public class ErrorController : Controller
    {
        // 500
        public ActionResult InternalServerError()
        {
            SetResponse(HttpStatusCode.InternalServerError);
            return View();
        }
        // 404
        public ActionResult NotFound()
        {
            SetResponse(HttpStatusCode.NotFound);
            return View();
        }
        // 403
        public ActionResult Forbidden()
        {
            SetResponse(HttpStatusCode.Forbidden);
            return View();
        }
        private void SetResponse(HttpStatusCode httpStatusCode)
        {
            Response.StatusCode = (int)httpStatusCode;
            Response.StatusDescription = HttpWorkerRequest.GetStatusDescription((int)httpStatusCode);
        }
        protected override void OnActionExecuted(ActionExecutedContext context)
        {
            // log
        }

2. Настройки Web.config для перенаправления в этот контроллер

<system.web>
    <customErrors mode="Off"/>
</system.web>
<system.webServer>    
    <httpErrors errorMode="Custom" existingResponse="Replace">
      <remove statusCode="403" />
      <remove statusCode="404" />
      <remove statusCode="500" />
      <error statusCode="403" path="/Error/Forbidden" responseMode="ExecuteURL" />
      <error statusCode="404" path="/Error/NotFound" responseMode="ExecuteURL" />
      <error statusCode="500" path="/Error/InternalServerError" responseMode="ExecuteURL" />
    </httpErrors>
  </system.webServer>

Добавить комментарий