いくつかの調査の後で、デフォルトのエラーページの動作を維持しながらasp.net core mvcでアプリケーションの例外をキャプチャする方法を見つけることができませんでした。アプリケーションエラーをカスタム処理するには、実際には2つの方法があります。最初と簡単な方法は、app.UseExceptionHandler("/Home/Error");
をStartup.csファイルで設定することですが、この方法では、デフォルトのDEVELOPMENTエラーページがかなり見えなくなりました。 asp.netコアMVCでのエラー処理をカスタマイズするための他のソリューションには、例外ハンドラをインラインで定義することですが、それは同様に無効にするために、デフォルトのエラーページを引き起こす:Asp.NetコアMVCキャプチャアプリケーションの例外の詳細
app.UseExceptionHandler(
options => {
options.Run(
async context =>
{
context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
context.Response.ContentType = "text/html";
var ex = context.Features.Get<IExceptionHandlerFeature>();
if (ex != null)
{
var err = $"<h1>Error: {ex.Error.Message}</h1>{ex.Error.StackTrace }";
await context.Response.WriteAsync(err).ConfigureAwait(false);
}
});
}
);
私はちょうどを上書きせずにエラーの詳細、をキャプチャする必要がありますデフォルトの動作(かなりデフォルトのエラーページなど)。私はカスタム例外ハンドラは必要ありませんが、実際には例外を取得する必要があります。私はアプリケーションレベルでそれをやりたいので、ExceptionHandlerAttribute
IExceptionFilter
を実装するカスタムは動作しません。その解決策は、デフォルトのエラーページを削除するだけでなく、ミドルウェアのエラーをキャッチする必要があります。アプローチに続いて適用されていません。
public class CustomExceptionFilter : IExceptionFilter
{
public void OnException(ExceptionContext context)
{
HttpStatusCode status = HttpStatusCode.InternalServerError;
String message = String.Empty;
var exceptionType = context.Exception.GetType();
if (exceptionType == typeof(UnauthorizedAccessException))
{
message = "Unauthorized Access";
status = HttpStatusCode.Unauthorized;
}
else if (exceptionType == typeof(NotImplementedException))
{
message = "A server error occurred.";
status = HttpStatusCode.NotImplemented;
}
else if (exceptionType == typeof(MyAppException))
{
message = context.Exception.ToString();
status = HttpStatusCode.InternalServerError;
}
else
{
message = context.Exception.Message;
status = HttpStatusCode.NotFound;
}
HttpResponse response = context.HttpContext.Response;
response.StatusCode = (int)status;
response.ContentType = "application/json";
var err = message + " " + context.Exception.StackTrace;
response.WriteAsync(err);
}
}