2009-10-08 73 views
9

这可能是一个菜鸟问题,但是;ActionResult上的自定义属性

比方说,我有一个ActionResult,我只想授予访问时间。

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

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

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

    return View(); 
} 

如何正是我会得到这个工作?

我已经做了一些关于创建自定义属性的研究,但我想我错过了关于如何使用它们的一点。

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

回答

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/

+0

谢谢罗伯特。这是很好的信息,但我需要以不同的方式重新提出问题。 :)但是这会很快派上用场。 – griegs 2009-10-08 20:36:36

+0

不应该是(当前<之前||当前>之后)而不是答案中表达的内容?区别在于二进制或与常规或! – 2015-07-02 02:27:41

2

您在.net mvc中查找的是Action Filters。

您需要扩展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

+0

若需授权有关的问题,你*必须*亚型AuthorizeAttribute而不是ActionFilterAttribute。见http://blogs.teamb.com/craigstuntz/2009/09/09/38390/ – 2009-10-08 15:38:08

+0

+1谢谢@Dean和@Craig – griegs 2009-10-08 20:37:07