SharpCoder
SharpCoder

Reputation: 19163

ASP.NET Web Api 2 - Log every incoming request for specific actions

I am working with ASP.NET Web Api 2. I have written two Filter Attributes which check every incoming request for specific headers and if the header keys are not present they return Unauthorized response to users.

This is what I am doing (one of the filters):

public class HeaderFilterAttribute : AuthorizationFilterAttribute
    {
        public override void OnAuthorization(HttpActionContext actionContext)
        {
            var req = actionContext.Request;


            if (! req.Headers.Contains("api-key") || req.Headers.GetValues("api-key") == null)
            {
                actionContext.Response = req.CreateResponse(HttpStatusCode.Unauthorized);
                actionContext.Response.Content = new StringContent("Token required", Encoding.UTF8, "text/html");
            }
        }
}

Now If the request contains valid header keys and they have reached the correct action method or endpoint, I want to log certain details about the request.

What is the right way to create a filter attribute for this scenario? Which method this filter attribute will override? Or can I achieve the desired result without creating a filter attribute. I think it will not make sense to override OnAuthorization()

Upvotes: 0

Views: 2363

Answers (1)

Jasen
Jasen

Reputation: 14250

Make a new filter extending ActionFilterAttribute. Your authorization filters will always run first then the logging filter logs your accepted requests.

public class MyLogFilterAttribute : ActionFilterAttribute
{
    public override OnActionExecuting(HttpActionContext actionContext)
    {
        // log info

        base.OnActionExecuting(actionContext);
    }
}

Add to a base controller class to log all actions.

[HeaderFilter]
[MyLogFilter]
public abstract class BaseApiController : ApiController
{
}

public class MyApiController : BaseApiController
{
}

Upvotes: 1

Related Questions