私の MVC アプリケーションでは、コントローラーのいくつかのメソッドを次のように装飾しました。
[PrincipalPermission(SecurityAction.Demand, Role = "Administrator")]
public ActionResult Create(FormCollection collection)
{
try {
...
}
catch {
return View();
}
}
実際、ログインしていないか、正しい役割を持っていない場合、MVC アプリケーションによって例外がスローされます。問題は、アプリケーションがエラー ページにリダイレクトされないことです。
次のようなベースコントローラーを作成してみました:
[HandleError]
public class BaseController : Controller
{
protected override void OnException(ExceptionContext filterContext)
{
// Make use of the exception later
this.Session["ErrorException"] = filterContext.Exception;
// Mark exception as handled
filterContext.ExceptionHandled = true;
// ... logging, etc
// Redirect
filterContext.Result = this.RedirectToAction("Error", "Home");
base.OnException(filterContext);
}
}
次に、ホームコントローラーと実際のビューにエラービューを追加します。問題は、Visual Studio でこれを試すと、保護されたアクション メソッドに入ったときに最初に例外が発生することです。
SecurityException was unhandled by the application
その後、Debug|Continue を実行する必要があり、その後にのみエラー ビューにリダイレクトされますが、本番アプリケーションではエラー ビューに直接移動する必要があるため、これは受け入れられません。