Home > Back-end >  ASP NET Core 5 - accessing (or passing) some value to exception filter
ASP NET Core 5 - accessing (or passing) some value to exception filter

Time:11-02

In C# .NET Core in a ASP NET 5 Core web app we have a custom exception filter:

public class CustomExceptionFilter : IExceptionFilter
{
   public void OnException(ExceptionContext context)
   {
     ...

Which is added to the base controller:

[TypeFilter(typeof(CustomExceptionFilter))]
public class MyBaseController : Controller
{

In the controller using the user login name we read some user properties from an SQL table and set some key properties to the session data - for now the most important is that is he/she is a "web developer" or not. When an exception happens, the exception filter catches that, but the error message is shown must be very different (in detail) if the user has this role or not.

My problem is: how to access the session instance from the exception filter, or better: how to set (pass) this Boolean value to the exception filter?

Thanks your suggestions in advance!

CodePudding user response:

The key to sharing information is by accessing the OnExceptions's ExceptionContext parameter and drilling into your items in the session.

That's context.HttpContext.Items where HttpContext is of type HttpContext and Items is an IDictionary<object, object>.

Of course, the session parameters need to be saved to session before the exception is thrown. You could do it a different way that may be appealing or not for you: catch the exception and throw a custom one in its place that has a boolean property to hold your value. Then you can access that exception's property in the filter via context.Exception after casting to your custom exception type.

  • Related