Should System.Web.Http.Filters.ActionFilterAttribute be in the same project as the controller?

I have a System.Web.Http.ApiController controller:

[LoggingFilterApi] public class BaseController : ApiController { public IHttpActionResult Ads(); } 

with a filter defined as follows:

 using System.Web.Http.Controllers; using System.Web.Http.Filters; namespace pecom.Common.Filters { public class LoggingFilterApiAttribute : ActionFilterAttribute { public override void OnActionExecuting(HttpActionContext ctx) { var msg = ctx.ActionDescriptor.ControllerDescriptor.ControllerType.Name + "." + ctx.ActionDescriptor.ActionName + "(" + ctx.Request.RequestUri.ToString(); ILog logger = LogManager.GetLogger(ctx.ActionDescriptor.ControllerDescriptor.ControllerType); logger.Info(msg); base.OnActionExecuting(ctx); } } } 

When LoggingFilterApiAttribute.cs is part of the .csproj controller, OnActionExecuting is called as expected. However, if LoggingFilterApiAttribute.cs moved to another .csproj (to facilitate code reuse), OnActionExecuting not called as expected. Weird

Has anyone seen this? While I duplicate filters for our projects, which is somewhat suboptimal. This is with ASP.NET MVC 5.2.

Cheers, Pete

+6
source share
2 answers

Most likely you have a mismatch in versions of Web Api 2. No matter which version of MVC your controller is Web Api, so you need to pay attention to the assemblies associated with Web Api.

I’m sure that if you check the version of System.Web.Http both in the MVC project and in your class library, they will be different, and therefore the detection mechanism will not be able to find your custom filter. Just fix the problem by matching them and it should work.

One easy way to fix this is to link to the latest Web Api 2 package ( Microsoft.AspNet.WebApi.Core ) in your class library and update the same package in your MVC project to match (or by messing with assembly redirection if you like that). If, for example, you simply copied the code into a class library and then used something like Resharper to resolve links, most likely he selected version 4.x from System.Web.Http from GAC instead of version 5.x, which you need here.

I tried what you did, and he reproduced your problem, and this procedure solved it.

+5
source

I managed to get it working in a few steps:

  • Create an MVC Application
  • Create an empty class library
  • add MVC environment to class library using nuget
  • add a link to System.Web in the class library project
  • Copy your code to the new class library class
  • Delete the code associated with the registrar for testing purposes
  • Replace HttpActionContext ctx with ActionExecutingContext filterContext
  • Replace ctx.Request.RequestUri.ToString () with filterContext.HttpContext.Request.Url
  • Link to the class library project
  • Add a filter to the home controller

Task completed

+1
source

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


All Articles