1

I'm getting a couple of errors when trying to use custom 404 and 500 error pages in MVC 2. I'm essentially trying to implement what I've found here: http://www.genericerror.com/blog/2009/01/27/ASPNetMVCCustomErrorPages.aspx So far, I have:

Placed the following line in my Web.config:

<customErrors mode="On" redirectMode="ResponseRewrite" defaultRedirect="~/Error/Http500" />

Placed the following route last in my route table:

routes.MapRoute(
    null,
    "{*path}",
    new { controller = "Error", action = "Http404" }
);

And, created the following controller:

public class ErrorController : Controller
{
    //
    // GET: /Error/Http500

    public ActionResult Http500()
    {
        Response.StatusCode = (int)HttpStatusCode.InternalServerError;
        return View("my500");
    }

    //
    // GET: /Error/Http404/Path

    public ActionResult Http404(string path)
    {
        Response.StatusCode = (int)HttpStatusCode.NotFound;
        return View("my404", path);
    }
}

With all of that, for 500 errors, the my500 view is not being rendered. Instead, it looks like the generic, default Error.aspx view is being displayed again. For 404 errors, I'm getting a YSOD telling me to turn on custom errors in my Web.config. I'm not sure what I'm missing, or if I'm even on the right track.

EDIT: Both views are in Views/Shared

4

1 に答える 1

1

HandleErrorHttp 500 エラーでは、コントローラーに属性が適用されているため、おそらく既定のページを取得しています。そこに向けたいエラータイプのHandleError属性でビューを指定できますが、 HttpExceptions を処理するために十分に開発されていません。コントローラーからこの属性を削除すると、デフォルトの asp.net が引き継ぎます。OnExceptionベースコントローラーでオーバーライドすることもできます。

Http 404 エラーには、意図せず使用しているオーバーロードがあります。 return View(string, string);パスをオブジェクトとしてキャストする (meh) か、名前付きパラメーターを使用する (万歳) と、ビューのモデルとしてパスが使用されます。現時点では、それが使用するマスター ページの名前であると認識されています。

これは難しい問題であり、詳細についてはこちらを参照してください。


少しつまらないことですが継承するクラスResponse.StatusCodeのメソッドでのみ設定することを強くお勧めします。概念的には、アクションの結果は、応答を構築する必要があるコードの一部であり、ここでコントローラーで行うように、その外部の部分を実装すると、非常に見つけにくいバグが発生する傾向があります。MVC2 に付属の では、結果とともに返されるビューを選択できないことはわかっていますが、 から独自の継承を展開するのはかなり簡単です。.Execute()ActionResultActionResultHttpStatusCodeResultViewResult

于 2011-04-25T19:56:35.107 に答える