I have the following Web API ActionFilterAttribute
namespace namespace.Filters {
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;
public class LogApiRequestActionFilterAttribute : ActionFilterAttribute {
public LogApiRequestActionFilterAttribute() {
}
private void logData(HttpActionContext actionContext) {
var controllerName = actionContext.ActionDescriptor.ControllerDescriptor.ControllerType.FullName;
var actionName = actionContext.ActionDescriptor.ActionName;
var parameters = "";
foreach (var item in actionContext.ActionArguments) {
parameters += string.Format("{0} = {1}, ", item.Key, item.Value);
}
if (parameters.Any()) {
parameters = parameters.Remove(parameters.Count() - 2);
}
var message = string.Format("{0}.{1}({2})", controllerName, actionName, parameters);
// Do the logging
}
public override void OnActionExecuting(HttpActionContext actionContext) {
logData(actionContext);
base.OnActionExecuting(actionContext);
}
}
}
When I add it globally over the WebApiConfig.cs
like this:
config.Filters.Add(new LogApiRequestActionFilterAttribute());
But the logData
method never gets called. Does anyone know why?
Did you decorate your controller (or any action method), with that filter ?
For e.g.
If the filter has to be applied only on certain action method, put the filter on that particular action method(s)
[LogApiRequestActionFilter]
public class YourController : ApiController
{ //--->controller level filter
[LogApiRequestActionFilter] //-->action level filter
public IHttpActionResult DoAction()
{
}
}
http request
. Check If your filter is registered or not
I just found my problem, thanks a lot to now he who must not be named.
My filter was properly registered and also perfectly loaded, just the method I was testing AND debugging with, wasn't called with a request. It was called from an razor helper and there the Request
-property is null
of course.
So the fix is to use an action which is called with an http request
and not just as normal method call.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With