asp.net-mvc – ActionResult上的自定义属性

前端之家收集整理的这篇文章主要介绍了asp.net-mvc – ActionResult上的自定义属性前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
这可能是菜鸟的问题,但是

假设我有一个ActionResult,我只想在几个小时后授予访问权限.

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

所以代码可能看起来像

  1. [AllowAccess(after="17:00:00",before="08:00:00")]
  2. public ActionResult AfterHoursPage()
  3. {
  4. //Do something not so interesting here;
  5.  
  6. return View();
  7. }

我该如何才能得到这个工作?

我已经做了一些关于创建自定义属性的研究,但是我觉得我错过了如何消耗它们.

请假设我知道几乎没有关于创建和使用它们.

解决方法

尝试这个(未经测试):
  1. public class AllowAccessAttribute : AuthorizeAttribute
  2. {
  3. public DateTime before;
  4. public DateTime after;
  5.  
  6. protected override bool AuthorizeCore(HttpContextBase httpContext)
  7. {
  8. if (httpContext == null)
  9. throw new ArgumentNullException("httpContext");
  10.  
  11. DateTime current = DateTime.Now;
  12.  
  13. if (current < before | current > after)
  14. return false;
  15.  
  16. return true;
  17. }
  18. }

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

猜你在找的asp.Net相关文章