9

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

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

假设我想用自定义属性装饰我的 ActionResult。

所以代码可能看起来像这样;

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

    return View();
}

我将如何让它发挥作用?

我已经对创建自定义属性进行了一些研究,但我认为我错过了如何使用它们的内容。

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

4

2 回答 2

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

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

于 2009-10-08T04:13:53.523 回答
2

您在 .net mvc 中寻找的是动作过滤器。

您将需要扩展 ActionFilterAttribute 类并在您的情况下实现 OnActionExecuting 方法。

请参阅: http ://www.asp.net/learn/mvc/tutorial-14-cs.aspx以获得对动作过滤器的体面介绍。

也有些类似的东西见:ASP.NET MVC - CustomeAuthorize filter action using an external website for loggin in the user

于 2009-10-08T04:12:11.107 回答