自定义属性上的ActionResult [英] Custom Attributes on ActionResult

查看:195
本文介绍了自定义属性上的ActionResult的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能是一个菜鸟的问题,但;

This is probably a rookie question but;

让我们说我有一个ActionResult,我只想小时后授予访问权限。

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

我们也可以说,我想我的装饰用的ActionResult一个自定义属性。

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

所以,code可能看起来像;

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();
}

如何究竟我会得到这个工作?

我已经做了关于创建自定义属性的一些研究,但我认为我缺少对如何消耗他们的位。

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

请假设我是知道的创建和使用,虽然它们pretty多罢了。

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

推荐答案

试试这个(未经测试):

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;
    }
}

此处了解详情:
<一href=\"http://schotime.net/blog/index.php/2009/02/17/custom-authorization-with-aspnet-mvc/\">http://schotime.net/blog/index.php/2009/02/17/custom-authorization-with-aspnet-mvc/

这篇关于自定义属性上的ActionResult的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆