Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom Attributes on ActionResult

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.

like image 540
griegs Avatar asked Oct 08 '09 03:10

griegs


People also ask

What can you say about ActionResult ()?

What is an ActionResult? An ActionResult is a return type of a controller method, also called an action method, and serves as the base class for *Result classes. Action methods return models to views, file streams, redirect to other controllers, or whatever is necessary for the task at hand.

Can I write ActionResult Instead of view result?

ActionResult is the best thing if you are returning different types of views. Show activity on this post. ActionResult is an abstract class, and it's base class for ViewResult class. In MVC framework, it uses ActionResult class to reference the object your action method returns.

What is ActionResult () in MVC?

An action result is what a controller action returns in response to a browser request. The ASP.NET MVC framework supports several types of action results including: ViewResult - Represents HTML and markup. EmptyResult - Represents no result.


1 Answers

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/

like image 153
Robert Harvey Avatar answered Oct 04 '22 00:10

Robert Harvey