ASP.NET MVC 4 Action Filter Issue

I want to create a filter and put it on actions that require access to the database. This filter will position the current unit of work, so I won’t need to call it manually one or more times in one action. I'm doing it:

public class DisposeUnitOfWorkAttribute :FilterAttribute, IActionFilter { public Task<HttpResponseMessage> ExecuteActionFilterAsync(HttpActionContext actionContext, CancellationToken cancellationToken, Func<Task<HttpResponseMessage>> continuation) { IUnitOfWork currentUnitOfWork = UnitOfWork.Current; if (currentUnitOfWork != null) { currentUnitOfWork.Dispose(); } return null; } public bool AllowMultiple { get { return false; } } } public class FilterConfig { public static void RegisterGlobalFilters(GlobalFilterCollection filters) { filters.Add(new DisposeUnitOfWorkAttribute()); filters.Add(new HandleErrorAttribute()); } } [DisposeUnitOfWork] public ViewResult Index() { var user = _usersRepository.Get(x => x.Username == "jack").ToList(); //UnitOfWork.Current.Dispose(); return View(); } 

I get an exception: The given filter instance must implement one or more of the following filter interfaces: IAuthorizationFilter, IActionFilter, IResultFilter, IExceptionFilter.

How can i fix this?

+4
source share
2 answers

Judging by your code, you are trying to use the filter as a web API filter, but adding it to the wrong filter collection in FilterConfig.cs (MVC-like)

 The given filter instance must implement one or more of the following filter interfaces: IAuthorizationFilter, IActionFilter, IResultFilter, IExceptionFilter. 

You should add the filter to the global web API filter collection, and not to WebApiConfig.cs:

  public static void Register(HttpConfiguration config) { // Add custom global filters // Handle validation errors config.Filters.Add(new DisposeUnitOfWorkAttribute()); 
+3
source

I assume you need to inherit from ActionFilterAttribute not FilterAttribute

 public class DisposeUnitOfWorkAttribute : ActionFilterAttribute { ... } 
+2
source

Source: https://habr.com/ru/post/1434045/


All Articles