Ajout d'un filtre d'exception personnalisé

This commit is contained in:
YuukanOO 2021-04-27 12:28:42 +02:00
parent d573536ba4
commit 4960449ed2
5 changed files with 37 additions and 1 deletions

View File

@ -24,6 +24,12 @@ namespace Website.Controllers
return View(); return View();
} }
[HttpGet("Status/404")]
public IActionResult PageNotFound()
{
return View();
}
public IActionResult Privacy() public IActionResult Privacy()
{ {
return View(); return View();

View File

@ -23,6 +23,8 @@ namespace Website
} }
[HttpGet("{controller}/detail/{linkId:guid}")] [HttpGet("{controller}/detail/{linkId:guid}")]
// [TypeFilter(typeof(CustomExceptionFilter))] // Permet d'appliquer un filtre ASP.Net
// sur une action uniquement (valable pour toutes les actions d'un controlleur si appliqué sur ce dernier)
public IActionResult Show(Guid linkId) public IActionResult Show(Guid linkId)
{ {
// ViewData["Comments"] = _commentService.GetAllLinkComments(linkId); // ViewData["Comments"] = _commentService.GetAllLinkComments(linkId);

View File

@ -0,0 +1,18 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
namespace Website
{
public class CustomExceptionFilter : IExceptionFilter
{
public void OnException(ExceptionContext context)
{
// FIXME en théorie, on aurait levé une exception personnalisée beaucoup
// moins globale pour éviter de catcher des choses non pertinentes.
if (context.Exception is System.InvalidOperationException)
{
context.Result = new NotFoundResult();
}
}
}
}

View File

@ -41,7 +41,11 @@ namespace Website
}); });
services.AddTransient<LinkService>(); services.AddTransient<LinkService>();
services.AddTransient<CommentService>(); services.AddTransient<CommentService>();
services.AddControllersWithViews();
services.AddControllersWithViews(options =>
{
options.Filters.Add<CustomExceptionFilter>();
});
} }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
@ -70,6 +74,7 @@ namespace Website
app.UseHsts(); app.UseHsts();
} }
app.UseHttpsRedirection(); app.UseHttpsRedirection();
app.UseStatusCodePagesWithRedirects("/Status/{0}");
app.UseStaticFiles(); app.UseStaticFiles();
app.UseRouting(); app.UseRouting();

View File

@ -0,0 +1,5 @@
@{
ViewData["Title"] = "Page not found";
}
<h1>Oh noes</h1>