ASP.NET MVCの「404ページが見つかりません」クエリを処理するキャッチオールルートを作成するにはどうすればよいですか?
-
10-07-2019 - |
質問
すべてをキャッチし、ユーザーをASP.NET MVCの404ビューにバウンスする最終ルートを作成することは可能ですか?
注:IIS設定でこれを設定したくありません。
解決
自分で答えを見つけました。
リチャードディンウォールがさまざまな戦略をたどる優れた記事を掲載しています。特にFilterAttributeソリューションが気に入っています。私は意地悪な周りに例外を投げるのが好きではないので、それを改善できるかどうかを確認します:)
global.asaxの場合、登録する最後のルートとしてこのコードを追加するだけです。
routes.MapRoute(
"404-PageNotFound",
"{*url}",
new { controller = "StaticContent", action = "PageNotFound" }
);
他のヒント
この質問は最初に出ましたが、簡単な答えは後の質問で出ました:
カスタムASP.NET MVC 404エラーページのルーティング
ErrorControllerを作成することにより、エラー処理が機能するようになりました。 この記事のビューを返します。また、「すべてをキャッチ」を追加する必要がありました。 global.asaxのルートへ。
そうでない場合、これらのエラーページにどのように到達するかわかりません Web.config ..?私のWeb.configは以下を指定する必要がありました:
customErrors mode="On" defaultRedirect="~/Error/Unknown"
そして私も追加しました:
error statusCode="404" redirect="~/Error/NotFound"
これがお役に立てば幸いです。
とても簡単なので、今はこの方法が大好きです:
<customErrors mode="On" defaultRedirect="~/Error/" redirectMode="ResponseRedirect">
<error statusCode="404" redirect="~/Error/PageNotFound/" />
</customErrors>
また、以下のようにGlobal.asax.csでNOT FOUNDエラーを処理できます
protected void Application_Error(object sender, EventArgs e)
{
Exception lastErrorInfo = Server.GetLastError();
Exception errorInfo = null;
bool isNotFound = false;
if (lastErrorInfo != null)
{
errorInfo = lastErrorInfo.GetBaseException();
var error = errorInfo as HttpException;
if (error != null)
isNotFound = error.GetHttpCode() == (int)HttpStatusCode.NotFound;
}
if (isNotFound)
{
Server.ClearError();
Response.Redirect("~/Error/NotFound");// Do what you need to render in view
}
}
プロジェクトルートweb.configファイルの下にこの行を追加します。
<system.webServer>
<httpErrors errorMode="Custom" existingResponse="Replace">
<remove statusCode="404" />
<error statusCode="404" responseMode="ExecuteURL" path="/Test/PageNotFound" />
<remove statusCode="500" />
<error statusCode="500" responseMode="ExecuteURL" path="/Test/PageNotFound" />
</httpErrors>
<modules>
<remove name="FormsAuthentication" />
</modules>
これは使用時に問題になる可能性があります
throw new HttpException(404);
あなたがそれを捕まえたいとき、私はあなたのウェブ設定を編集する他の方法を知りません。
キャッチオールルートを作成する代わりに、 MvcApplication
に追加します/ 9026907/145173 "> Marco's Better-Than-Unicorns MVC 404 Answer 。
RouterConfig.cs
内に、次のコードを追加します。
routes.MapRoute(
name: "Error",
url: "{id}",
defaults: new
{
controller = "Error",
action = "PageNotFound"
});
ルートを解決できない場合、MVCフレームワークは404エラーを通過します。 最適なアプローチは、例外フィルターを使用することです...カスタム例外フィルターを作成し、次のように作成します。
public class RouteNotFoundAttribute : FilterAttribute, IExceptionFilter {
public void OnException(ExceptionContext filterContext) {
filterContext.Result = new RedirectResult("~/Content/RouteNotFound.html");
}
}