9

This is probably a rookie question but;

Let's say I have an ActionResult that I only want to grant access to after hours.

Let's also say that I want to decorate my ActionResult with a custom attribute.

So the code might look something like;

[AllowAccess(after="17:00:00", before="08:00:00")]
public ActionResult AfterHoursPage()
{
    //Do something not so interesting here;

    return View();
}

How exactly would I get this to work?

I've done some research on creating Custom Attributes but I think I'm missing the bit on how to consume them.

Please assume I know pretty much nothing about creating and using them though.

griegs
  • 22,624
  • 33
  • 128
  • 205

2 Answers2

14

Try this (untested):

public class AllowAccessAttribute : AuthorizeAttribute
{
    public DateTime before;
    public DateTime after;

    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        if (httpContext == null)
            throw new ArgumentNullException("httpContext");

        DateTime current = DateTime.Now;

        if (current < before | current > after)
            return false;

        return true;
    }
}

More info here: http://schotime.net/blog/index.php/2009/02/17/custom-authorization-with-aspnet-mvc/

Robert Harvey
  • 178,213
  • 47
  • 333
  • 501
  • Thank you Robert. This is great info though I need to re-ask the question in a different way. :) But this will come in handy real soon now. – griegs Oct 08 '09 at 20:36
  • Shouldn't it be (current < before || current > after) instead of what is expressed in the answer? The difference being binary or vs. regular or! – Parth Shah Jul 02 '15 at 02:27
2

What you are looking for in .net mvc are Action Filters.

You will need to extend the ActionFilterAttribute class and implement the OnActionExecuting method in your case.

See: http://www.asp.net/learn/mvc/tutorial-14-cs.aspx for a decent introduction to action filters.

Also for something slightly similar see: ASP.NET MVC - CustomeAuthorize filter action using an external website for loggin in the user

Community
  • 1
  • 1
Dean Johnston
  • 446
  • 4
  • 7
  • For authorization-related concerns, you *must* subtype AuthorizeAttribute, not ActionFilterAttribute. See http://blogs.teamb.com/craigstuntz/2009/09/09/38390/ – Craig Stuntz Oct 08 '09 at 15:38