I'm new to c# and .net in general (not to programming at all) and i have one small question about filter attributes in c#
Consider having filter with type of IActionFilter like this:

My question is how could i catch this context.Result property to use it like a return type? For example, i have a controller method that should normally return (for example) response 200, but under some exceptions that can be handled inside my filter, the filter itself could return 404. So back to the equestion, is it possible to catch this context.Result? And if so, what is the best practives to do it?

Jignesh KumarRank #91 · 22.9K reputationPosted Jan 22, 2023, 10:48 PM EST
Hello,
You can achieve using Exception filter attribute, please refer below links,
https://www.c-sharpcorner.com/UploadFile/0ef46a/exception-filters-in-mvc/
https://www.c-sharpcorner.com/article/custom-exception-filter-in-asp-net-mvc/
Vishal JoshiRank #377 · 6.7K reputationPosted Jan 22, 2023, 11:05 PM EST
Hello
You can try ExceptionFilterAttribute Class to handle exceptions at the global level for all actions. check below code for the sample.
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Filters; public class CustomExceptionFilterAttribute : ExceptionFilterAttribute { public override void OnException(ExceptionContext context) { // code ... } }I then add the filter to the whole controller or action as per requirement.
[ServiceFilter(typeof(CustomExceptionFilterAttribute))] public class MyController : ControllerBase { }in Startup.cs, ConfigureServices, add DI support:
Thanks
Mohammad JouhariRank #7,688 · 236 reputationPosted Feb 8, 2023, 5:41 PM EST
if you are using .net core, why not creating a midlleware that catches the exception refer to this article https://briancaos.wordpress.com/2019/12/06/net-core-api-catch-exceptions-using-a-middleware/