0

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()

0

1 Answer 1

1

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 { } 
Sign up to request clarification or add additional context in comments.

2 Comments

How to pass dependency in MyLogFilter e.g. logger instance?
@HimalayaGarg that's out-of-scope for this question. But it would depend on your logger and DI framework. I'm sure it's been answered on SO before.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.