1

I do some Caching-Checks (etag) in my base controller called "CachingController"

public CachingController:Controller {
   public CachingController() {
      if (IsKnownEtag(Request.Headers["If-None-Match"])) {
         Response.StatusCode=304;
      }
   }
}

public MyController:CachingController {
  public ActionResult IsMagic(string dragonName) {   
     var isMagic=dragonName=="Puff";
     // ...
     SaveEtag();
     return new ActionResult(isMagic);
  }
}

So in the Constructor of my Base Controller I check if the Etag is valid. If it is, I want to return the status code. After I set the Status code I do not want that the Controller Action is still called. How can I do this without modifying each Action?

1
  • try Response.End(); after Response.StatusCode=304; Commented Apr 21, 2016 at 13:37

1 Answer 1

2

Move the etag logic to an ActionFilterAttribute instead:

public class EtagFilter : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        if(IsKnownEtag(filterContext.HttpContext.Request.Headers["If-None-Match"]))
        {
            filterContext.Result = new HttpStatusCodeResult(HttpStatusCode.NotModified);
        }
    }

    //...
}

And then use it in your controller:

public class MyController : CachingController
{
    [EtagFilter]
    public ActionResult IsMagic(string dragonName)
    {
        var isMagic = dragonName == "Puff";
        // ...
        SaveEtag();
        return new ActionResult(isMagic);
    }
}

Also, move the SaveEtag() method to the filter so you keep that logic away from your controller.

Sign up to request clarification or add additional context in comments.

1 Comment

Sadly I cannot move the SaveETag() into the filter cause I make some validation-operations (Action 1 causes also Action 4 and 6 to revalidate etc.). Nonetheless. Your answer worked fine, thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.