ActionResult上的自定义属性

gri*_*egs 9 asp.net-mvc custom-attributes

这可能是一个新手问题但是;

假设我有一个ActionResult,我只想在下班后授予访问权限.

我们还要说我想用自定义属性装饰我的ActionResult.

所以代码可能看起来像;

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

    return View();
}
Run Code Online (Sandbox Code Playgroud)

如何准确地我会得到这个工作?

我已经做过一些关于创建自定义属性的研究,但我想我对如何使用它们缺乏了解.

请假设我对创建和使用它们几乎一无所知.

Rob*_*vey 14

试试这个(未经测试):

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

更多信息:http: //schotime.net/blog/index.php/2009/02/17/custom-authorization-with-aspnet-mvc/