Atributos personalizados no ActionResult
-
20-09-2019 - |
Pergunta
Esta é provavelmente uma pergunta de novato, mas;
Digamos que eu tenha um ActionResult que eu só quero conceder acesso após horas.
Digamos também que quero decorar meu ActionResult com um atributo personalizado.
Portanto, o código pode parecer algo assim;
[AllowAccess(after="17:00:00", before="08:00:00")]
public ActionResult AfterHoursPage()
{
//Do something not so interesting here;
return View();
}
Quão exatamente Eu faria isso funcionar?
Fiz algumas pesquisas sobre a criação de atributos personalizados, mas acho que estou perdendo um pouco sobre como consumi -los.
Por favor, assuma que eu sei praticamente nada sobre criá -los e usá -los.
Solução
Try this (untested):
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;
}
}
More info here: http://schotime.net/blog/index.php/2009/02/17/custom-authorization-with-aspnet-mvc/
Outras dicas
What you are looking for in .net mvc are Action Filters.
You will need to extend the ActionFilterAttribute class and implement the OnActionExecuting method in your case.
See: http://www.asp.net/learn/mvc/tutorial-14-cs.aspx for a decent introduction to action filters.
Also for something slightly similar see: ASP.NET MVC - CustomeAuthorize filter action using an external website for loggin in the user