Activity: Writing a Custom Filter

Scenario
You need to write a filter that will only allow the applied action on Sundays. How would you do that?

Aim
To write a custom filter.

Steps for completion

  1. Open your editor and write this code:

Go to https://goo.gl/9QKgbS to access the code.
public class SundayFilter : Attribute, IActionFilter
{
public void OnActionExecuting(ActionExecutingContext context)
{
if (DateTime.Now.DayOfWeek != DayOfWeek.Sunday)
context.Result = new ContentResult()
{
Content = "Sorry only on sundays!"
};
}
public void OnActionExecuted(ActionExecutedContext context)
{
// do something after the action executes
}
}

Setting results in the filter causes short circuiting, so our action does not run.
  1. Now, we can apply this attribute onto our actions:

Go to https://goo.gl/x1ij7Z to access the code.
[SundayFilter]
public IActionResult Employee()
{


}

You have successfully created a custom filter.