With ASP.Net Core 2, how can you access the Controller instance that ExceptionFilterAttribute applies to?
Is there a better way to get general βbasicβ properties and methods of a controller, etc. Now in Core? For example, put it at a higher level, for example, Startup?
Before Core, in MVC 4, I would do something like this:
[ApiTracking]
[ApiException]
public class BaseApiController : ApiController
{
private Common.Models.Tracking _Tracking = null;
public Common.Models.Tracking Tracking
{
get
{
if(_Tracking == null)
_Tracking = new Common.Models.Tracking();
return _Tracking;
}
}
}
public class ApiExceptionAttribute : ExceptionFilterAttribute
{
public override void OnException(HttpActionExecutedContext cntxt)
{
BaseApiController ctrl = cntxt.ActionContext.ControllerContext.Controller as BaseApiController;
if (ctrl != null)
ctrl.Tracking.Exception(cntxt.Exception, true);
base.OnException(actionExecutedContext);
}
}
public class ApiTrackingAttribute : System.Web.Http.Filters.ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext cntxt)
{
}
public override void OnActionExecuted(HttpActionExecutedContext cntxt)
{
BaseApiController ctrl = cntxt.ActionContext.ControllerContext.Controller as BaseApiController;
if (ctrl != null)
ctrl.Tracking.Save();
}
}
source
share