Question

I have created an ActionFilterAttribute

public class LoggingNHibernateSessionAttribute : ActionFilterAttribute

The purpose of the filter as name indicates is logging and opens and commits a transaction, before and after target action respectively.

I have a WebApi(myAPI) project (MVC4) and a WebApplication(myContent).

Each Api Controller in myAPI is decorated with this attribute.

using myApp.Web.Common.Filters;

namespace myAPI.Web.Api.Controllers
{
    [LoggingNHibernateSession]
    public class CategoriesController : ApiController
    {

When a Http action (Get/Post) is executed inside the ApiController, the ActionFilter gets executed and it works fine as expected.

The problem: In the WebApplication(myContent), I have decorated those controllers as well with the ActionFilter.

using myApp.Web.Common.Filters;

namespace myContent.Web.Content.Places.Controllers
{
    [LoggingNHibernateSession]
    public class PlacesController : Controller
    {

But here, when an action is executed inside the controller, the ActionFilter is not getting executed.

The ActionFilter belongs to System.Web.Http.Filters;

I have read some posts, and they said to use System.Web.Mvc filters. So I changed the ActionFilter to be from System.Web.Mvc And when I switched that, the ActionFilter stopped working in WebApi as well.

What am I doing wrong here?

Was it helpful?

Solution

Although WebApi and MVC are very similar and technically consist of largely the same code, WebApi was created by copying all the code rather than through reuse. This happened, I'm told, because the WCF team didn't want a dependency on the MVC assemblies.

Therefore, code (such as your custom filter) compiled against one assembly will not work in the context of the other.

The solution is to duplicate your own code and compile against both sets of assemblies. You could also set up a build system to cross-compile the same code files using different reference assemblies.

It's truly sad when internal company politics result in something like this. The least they could do was acknowledge the problem and add some proper cross-compile support to their tooling, but alas, I digress.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top