MVC構造体を使用しており、複数のC#コントローラを使用しています。すべてのコントローラメソッドにcatchステートメントを追加するのではなく、すべてのコントローラからWebコンフィグレーションですべての例外をキャッチする方法C#
ありがとうございました。
MVC構造体を使用しており、複数のC#コントローラを使用しています。すべてのコントローラメソッドにcatchステートメントを追加するのではなく、すべてのコントローラからWebコンフィグレーションですべての例外をキャッチする方法C#
ありがとうございました。
OnException
イベントで独自のベースコントローラを作成し、例外を処理することができます。
public class BaseController : Controller
{
protected override void OnException(ExceptionContext filterContext)
{
// to do : Log the exception (filterContext.Exception)
// and redirect/return error view
filterContext.ExceptionHandled = true;
// If the exception occurred in an ajax call. Send a json response back
// (you need to parse this and display to user as needed at client side)
if (filterContext.HttpContext.Request.Headers["X-Requested-With"]
=="XMLHttpRequest")
{
filterContext.Result = new JsonResult
{
JsonRequestBehavior = JsonRequestBehavior.AllowGet,
Data = new { Error = true, Message = filterContext.Exception.Message }
};
filterContext.HttpContext.Response.StatusCode = 500; // Set as needed
}
else
{
filterContext.Result = new ViewResult { ViewName = "Error.cshtml" };
//Assuming the view exists in the "~/Views/Shared" folder
}
}
}
アヤックス以外のリクエストの場合は、Error.cshtml
をユーザーに表示します。 Error.cshtml
を表示する代わりにError
アクションメソッドにリダイレクト(新しいGET呼び出し)を行う場合は、ViewResult
をRedirectToRouteResult
に置き換えることができます。
filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary {
{"controller", "Home"}, {"action", "Error"}
};
は今、あなたの他のコントローラは、あなたが望むものは明らかではない。この
public class HomeController : BaseController
{
public ActionResult Die()
{
throw new Exception("Bad code!");
}
}
public class ProductsController : BaseController
{
public ActionResult Index()
{
var arr =new int[2];
var thisShouldCrash = arr[10];
return View();
}
}
ありがとうございました。私はこれを試してみる。 @shyju – bethisdname
から継承しています。もっと説明してください。 – NicoRiff