【问题标题】:Custom Attributes on ActionResultActionResult 上的自定义属性
【发布时间】:2009-10-08 03:52:09
【问题描述】:

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

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

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

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

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

    return View();
}

我将如何确切地让它发挥作用?

我对创建自定义属性进行了一些研究,但我认为我缺少关于如何使用它们的部分。

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

【问题讨论】:

    标签: asp.net-mvc custom-attributes


    【解决方案1】:

    试试这个(未经测试):

    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/

    【讨论】:

    • 谢谢罗伯特。这是很好的信息,尽管我需要以不同的方式重新提出问题。 :) 但这很快就会派上用场了。
    • 不应该是(当前之后)而不是答案中所表达的吗?区别在于二进制或与常规或!
    【解决方案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

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-31
    • 1970-01-01
    • 2012-02-15
    相关资源
    最近更新 更多