2009-10-08 41 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