part 2: The Demo
We have two ways (at least) to intercept requests on webapi before they arrive to controllers:
- MessageHandler: as CacheCow do.
- ActionFilterAttribute: I will use this.
ActionFilterAttribute expose the method OnActionExecuting(), it occurs before the controller's action method is invoked.
All we need to do is create a class derived from ActionAttributeFilter and override method OnActionExecuting().
public class ETagAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
// we will put our ode here
}
}
Now add the attribute to our test controller's action:
[ETag]
[HttpGet]
[Route("api/values/{id}")]
public string Get(int id)
{
var r = new Random();
var data = $"{r.Next(0, 10)} {r.Next(0, 10)} {r.Next(0, 10)} {r.Next(0, 10)}";
return $"value request: {id}. {data}";
}
Put a breakpoint on Etag attribute method, start on Debug mode (F5) and do a GET request to the test resource "api/values/5"
We are now stopped inside our attribute class and all request information is available there.
I'm requesting the same resource this time but populating the If-None-Match header,
Run with F5 again and lets check the actionContext param:
Aucun commentaire:
Enregistrer un commentaire