web-dev-qa-db-ja.com

ASP.NET MVC 4でカスタムエラーページを機能させる方法

500、404、403のカスタムエラーページが表示されるようにします。

  1. 次のようにweb.configでカスタムエラーを有効にしました。

    <customErrors mode="On" 
                  defaultRedirect="~/Views/Shared/Error.cshtml">
    
        <error statusCode="403" 
               redirect="~/Views/Shared/UnauthorizedAccess.cshtml" />
    
        <error statusCode="404" 
               redirect="~/Views/Shared/FileNotFound.cshtml" />
    
    </customErrors>
    
  2. 次のようにHandleErrorAttributeクラスのグローバルアクションフィルタとしてFilterConfigを登録しました。

    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(new CustomHandleErrorAttribute());
        filters.Add(new AuthorizeAttribute());
    }
    
  3. 上記の各メッセージに対してカスタムエラーページを作成しました。デフォルトの500はすでに出荷されています。

  4. 各カスタムエラーページビューで、そのページのモデルがSystem.Web.Mvc.HandleErrorInfoであると宣言されています

500の場合、カスタムエラーページが表示されます。他の人にとっては違います。

足りないものはありますか。

OnExceptionクラスのHandleErrorAttributeメソッドのコードを読んでカスタムエラーを表示するのがこれだけではなく、500個しか扱っていないようです。

他のエラーを処理するために何をしなければなりませんか?

233
Water Cooler v2

私の現在の設定は(MVC3上ですが、まだ適用されると思います)、ErrorControllerを持っていることに依存しているので、私は以下を使います:

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

そして、コントローラーには以下が含まれています。

public class ErrorController : Controller
{
    public ViewResult Index()
    {
        return View("Error");
    }
    public ViewResult NotFound()
    {
        Response.StatusCode = 404;  //you may want to set this to 200
        return View("NotFound");
    }
}

そして、あなたがそれらを実装するのと同じ方法でビューを表示します。ただし、アプリケーションがデバッグモードの場合にスタックトレースとエラー情報を表示するために、少しロジックを追加する傾向があります。したがって、Error.cshtmlは次のようになります。

@model System.Web.Mvc.HandleErrorInfo
@{
    Layout = "_Layout.cshtml";
    ViewBag.Title = "Error";
}
<div class="list-header clearfix">
    <span>Error</span>
</div>
<div class="list-sfs-holder">
    <div class="alert alert-error">
        An unexpected error has occurred. Please contact the system administrator.
    </div>
    @if (Model != null && HttpContext.Current.IsDebuggingEnabled)
    {
        <div>
            <p>
                <b>Exception:</b> @Model.Exception.Message<br />
                <b>Controller:</b> @Model.ControllerName<br />
                <b>Action:</b> @Model.ActionName
            </p>
            <div style="overflow:scroll">
                <pre>
                    @Model.Exception.StackTrace
                </pre>
            </div>
        </div>
    }
</div>
336
Pablo Romeo

私はpabloの解決をしましたが、私はいつもエラーを抱えていました(MVC4)

ビュー 'Error'またはそのマスターが見つからないか、検索エンジンがサポートしているビューエンジンがありません。

これを取り除くには、行を削除してください

 filters.Add(new HandleErrorAttribute());

filterConfig.cs内

39
Machinegon

私は他の投稿された解決策より少ないコーディングを必要とする何かをします。

まず、私のweb.configには、次のものがあります。

<customErrors mode="On" defaultRedirect="~/ErrorPage/Oops">
   <error redirect="~/ErrorPage/Oops/404" statusCode="404" />
   <error redirect="~/ErrorPage/Oops/500" statusCode="500" />
</customErrors>

そして、コントローラ(/Controllers/ErrorPageController.cs)には以下が含まれています。

public class ErrorPageController : Controller
{
    public ActionResult Oops(int id)
    {
        Response.StatusCode = id;

        return View();
    }
}

そして最後に、このビューには次のものが含まれています(簡単にするために省略してありますが、それが原因である可能性があります。

@{ ViewBag.Title = "Oops! Error Encountered"; }

<section id="Page">
  <div class="col-xs-12 well">
    <table cellspacing="5" cellpadding="3" style="background-color:#fff;width:100%;" class="table-responsive">
      <tbody>
        <tr>
          <td valign="top" align="left" id="tableProps">
            <img width="25" height="33" src="~/Images/PageError.gif" id="pagerrorImg">
          </td>
          <td width="360" valign="middle" align="left" id="tableProps2">
            <h1 style="COLOR: black; FONT: 13pt/15pt verdana" id="errortype"><span id="errorText">@Response.Status</span></h1>
          </td>
        </tr>
        <tr>
          <td width="400" colspan="2" id="tablePropsWidth"><font style="COLOR: black; FONT: 8pt/11pt verdana">Possible causes:</font>
          </td>
        </tr>
        <tr>
          <td width="400" colspan="2" id="tablePropsWidth2">
            <font style="COLOR: black; FONT: 8pt/11pt verdana" id="LID1">
                            <hr>
                            <ul>
                                <li id="list1">
                                    <span class="infotext">
                                        <strong>Baptist explanation: </strong>There
                                        must be sin in your life. Everyone else opened it fine.<br>
                                    </span>
                                </li>
                                <li>
                                    <span class="infotext">
                                        <strong>Presbyterian explanation: </strong>It's
                                        not God's will for you to open this link.<br>
                                    </span>
                                </li>
                                <li>
                                    <span class="infotext">
                                        <strong> Word of Faith explanation:</strong>
                                        You lack the faith to open this link. Your negative words have prevented
                                        you from realizing this link's fulfillment.<br>
                                    </span>
                                </li>
                                <li>
                                    <span class="infotext">
                                        <strong>Charismatic explanation: </strong>Thou
                                        art loosed! Be commanded to OPEN!<br>
                                    </span>
                                </li>
                                <li>
                                    <span class="infotext">
                                        <strong>Unitarian explanation:</strong> All
                                        links are equal, so if this link doesn't work for you, feel free to
                                        experiment with other links that might bring you joy and fulfillment.<br>
                                    </span>
                                </li>
                                <li>
                                    <span class="infotext">
                                        <strong>Buddhist explanation:</strong> .........................<br>
                                    </span>
                                </li>
                                <li>
                                    <span class="infotext">
                                        <strong>Episcopalian explanation:</strong>
                                        Are you saying you have something against homosexuals?<br>
                                    </span>
                                </li>
                                <li>
                                    <span class="infotext">
                                        <strong>Christian Science explanation: </strong>There
                                        really is no link.<br>
                                    </span>
                                </li>
                                <li>
                                    <span class="infotext">
                                        <strong>Atheist explanation: </strong>The only
                                        reason you think this link exists is because you needed to invent it.<br>
                                    </span>
                                </li>
                                <li>
                                    <span class="infotext">
                                        <strong>Church counselor's explanation:</strong>
                                        And what did you feel when the link would not open?
                                    </span>
                                </li>
                            </ul>
                            <p>
                                <br>
                            </p>
                            <h2 style="font:8pt/11pt verdana; color:black" id="ietext">
                                <img width="16" height="16" align="top" src="~/Images/Search.gif">
                                HTTP @Response.StatusCode - @Response.StatusDescription <br>
                            </h2>
                        </font>
          </td>
        </tr>
      </tbody>
    </table>
  </div>
</section>

それはそれと同じくらい簡単です。それはより詳細なエラー情報を提供するように容易に拡張することができますが、 ELMAH は私にとってそれを扱います。

20
coderpros

Global.asax.csファイルを使用することをお勧めします。

 protected void Application_Error(Object sender, EventArgs e)
{
    var exception = Server.GetLastError();
    if (exception is HttpUnhandledException)
    {
        Server.Transfer("~/Error.aspx");
    }
    if (exception != null)
    {
        Server.Transfer("~/Error.aspx");
    }
    try
    {
        // This is to stop a problem where we were seeing "gibberish" in the
        // chrome and firefox browsers
        HttpApplication app = sender as HttpApplication;
        app.Response.Filter = null;
    }
    catch
    {
    }
}
12
maxspan

ここで混乱したいくつかのステップがあるようです。私は最初からやったことを進めます。

  1. ErrorPageコントローラを作成する

    public class ErrorPageController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }
    
        public ActionResult Oops(int id)
        {
            Response.StatusCode = id;
            return View();
        }
    }
    
  2. これら2つのアクションのビューを追加します(右クリック - >ビューの追加)。これらはErrorPageというフォルダに表示されます。

  3. App_Start内でFilterConfig.csを開き、エラー処理フィルタをコメントアウトします。

    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        // Remove this filter because we want to handle errors ourselves via the ErrorPage controller
        //filters.Add(new HandleErrorAttribute());
    }
    
  4. Web.config内の<customerErrors>の下に、以下のSystem.Webエントリを追加します。

    <customErrors mode="On" defaultRedirect="~/ErrorPage/Oops">
        <error redirect="~/ErrorPage/Oops/404" statusCode="404" />
        <error redirect="~/ErrorPage/Oops/500" statusCode="500" />
    </customErrors>
    
  5. テストする(もちろん)。コード内で未処理の例外をスローし、それがID 500のページに移動するのを確認してから、存在しないページへのURLを使用して404を確認します。

9
VictorySaber

Maxspanによって投稿された答えに基づいて、私はGitHub上で最小の サンプルプロジェクトをまとめました すべての作業部分を示しました。

基本的に、global.asax.csApplication_Errorメソッドを追加して例外をインターセプトし、リダイレクトする機会を与えます(より正確には、error request)をカスタムエラーページに転送します。

    protected void Application_Error(Object sender, EventArgs e)
    {
        // See http://stackoverflow.com/questions/13905164/how-to-make-custom-error-pages-work-in-asp-net-mvc-4
        // for additional context on use of this technique

        var exception = Server.GetLastError();
        if (exception != null)
        {
            // This would be a good place to log any relevant details about the exception.
            // Since we are going to pass exception information to our error page via querystring,
            // it will only be practical to issue a short message. Further detail would have to be logged somewhere.

            // This will invoke our error page, passing the exception message via querystring parameter
            // Note that we chose to use Server.TransferRequest, which is only supported in IIS 7 and above.
            // As an alternative, Response.Redirect could be used instead.
            // Server.Transfer does not work (see https://support.Microsoft.com/en-us/kb/320439 )
            Server.TransferRequest("~/Error?Message=" + exception.Message);
        }

    }

エラーコントローラ:

/// <summary>
/// This controller exists to provide the error page
/// </summary>
public class ErrorController : Controller
{
    /// <summary>
    /// This action represents the error page
    /// </summary>
    /// <param name="Message">Error message to be displayed (provided via querystring parameter - a design choice)</param>
    /// <returns></returns>
    public ActionResult Index(string Message)
    {
        // We choose to use the ViewBag to communicate the error message to the view
        ViewBag.Message = Message;
        return View();
    }

}

エラーページ

<!DOCTYPE html>

<html>
<head>
    <title>Error</title>
</head>
<body>

    <h2>My Error</h2>
    <p>@ViewBag.Message</p>
</body>
</html>

FilterConfig.csfilters.Add(new HandleErrorAttribute())を無効にする/削除する以外には、何も関与していません。

public class FilterConfig
{
    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        //filters.Add(new HandleErrorAttribute()); // <== disable/remove
    }
}

実装は非常に単純ですが、このアプローチで私が見る1つの欠点は、クエリ文字列を使用して例外情報をターゲットのエラーページに配信することです。

6
user3380909

私はすべてをセットアップしましたが、ローカルの開発サーバーではすべてうまくいったにもかかわらず、ステージングサーバーでステータスコード500の適切なエラーページを見ることができませんでした。

私は Rick Strahlからこのブログ記事 を見つけて私を助けました。

カスタムエラー処理コードにResponse.TrySkipIisCustomErrors = true;を追加する必要がありました。

2
DCShannon

これが私の解決策です。私の意見では[ExportModelStateToTempData]/[ImportModelStateFromTempData]を使うのは不快です。

〜/ビュー/ホーム/ Error.cshtml:

@{
    ViewBag.Title = "Error";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>Error</h2>
<hr/>

<div style="min-height: 400px;">

    @Html.ValidationMessage("Error")

    <br />
    <br />

    <button onclick="Error_goBack()" class="k-button">Go Back</button>
    <script>
        function Error_goBack() {
            window.history.back()
        }
    </script>

</div>

〜/コントローラ/ HomeController.sc:

public class HomeController : BaseController
{
    public ActionResult Index()
    {
        return View();
    }

    public ActionResult Error()
    {
        return this.View();
    }

    ...
}

〜/コントローラ/ BaseController.sc:

public class BaseController : Controller
{
    public BaseController() { }

    protected override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        if (filterContext.Result is ViewResult)
        {
            if (filterContext.Controller.TempData.ContainsKey("Error"))
            {
                var modelState = filterContext.Controller.TempData["Error"] as ModelState;
                filterContext.Controller.ViewData.ModelState.Merge(new ModelStateDictionary() { new KeyValuePair<string, ModelState>("Error", modelState) });
                filterContext.Controller.TempData.Remove("Error");
            }
        }
        if ((filterContext.Result is RedirectResult) || (filterContext.Result is RedirectToRouteResult))
        {
            if (filterContext.Controller.ViewData.ModelState.ContainsKey("Error"))
            {
                filterContext.Controller.TempData["Error"] = filterContext.Controller.ViewData.ModelState["Error"];
            }
        }

        base.OnActionExecuted(filterContext);
    }
}

〜/コントローラ/ MyController.sc:

public class MyController : BaseController
{
    public ActionResult Index()
    {
        return View();
    }

    public ActionResult Details(int id)
    {
        if (id != 5)
        {
            ModelState.AddModelError("Error", "Specified row does not exist.");
            return RedirectToAction("Error", "Home");
        }
        else
        {
            return View("Specified row exists.");
        }
    }
}

私はあなたが成功したプロジェクトを願っています;-)

2
ADM-IT

Global.csをハックしたり、HandleErrorAttributeを操作したり、Response.TrySkipIisCustomErrorsを実行したり、Application_Errorをフックしたりしなくても、エラーが正しく機能するようにできます。

System.web内(通常どおり、オン/オフ)

<customErrors mode="On">
  <error redirect="/error/401" statusCode="401" />
  <error redirect="/error/500" statusCode="500" />
</customErrors>

そしてsystem.webServerに

<httpErrors existingResponse="PassThrough" />

これで物事は予想通りに振る舞うはずで、ErrorControllerを使って必要なものを何でも表示することができます。

1
Robert

パーティーに遅刻したようですが、こちらもチェックしてください。

system.webではreturn HttpNotFound()のようなアプリケーション内の例外をキャッシュするために

  <system.web>
    <customErrors mode="RemoteOnly">
      <error statusCode="404" redirect="/page-not-found" />
      <error statusCode="500" redirect="/internal-server-error" />
    </customErrors>
  </system.web>

IISで捕捉され、asp.netフレームワークに到達しなかったエラーを検出するためのsystem.webServer

 <system.webServer>
    <httpErrors errorMode="DetailedLocalOnly">
      <remove statusCode="404"/>
      <error statusCode="404" path="/page-not-found" responseMode="Redirect"/>
      <remove statusCode="500"/>
      <error statusCode="500" path="/internal-server-error" responseMode="Redirect"/>
  </system.webServer>

最後の例では、クライアントの応答が心配な場合は、responseMode="Redirect"responseMode="File"に変更し、静的なhtmlファイルを提供します。これは、応答コード200のわかりやすいページが表示されるためです。

0
OrElse

以下のようにweb.configでsystem.webserverタグの下にこれを追加します。

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

としてコントローラを追加します。

public class ErrorController : Controller
{
    //
    // GET: /Error/
    [GET("/Error/NotFound")]
    public ActionResult NotFound()
    {
        Response.StatusCode = 404;

        return View();
    }

    [GET("/Error/ErrorPage")]
    public ActionResult ErrorPage()
    {
        Response.StatusCode = 500;

        return View();
    }
}

そして彼らの尊敬される見解を加えれば、これは間違いなくうまくいくでしょう。

この解決策私はそれを見つけた: 海王星世紀

0
Dpk-Kumar