Custom Attributes on ActionResult

痞子三分冷 提交于 2019-11-28 03:17:39

问题


This is probably a rookie question but;

Let's say I have an ActionResult that I only want to grant access to after hours.

Let's also say that I want to decorate my ActionResult with a custom attribute.

So the code might look something like;

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

    return View();
}

How exactly would I get this to work?

I've done some research on creating Custom Attributes but I think I'm missing the bit on how to consume them.

Please assume I know pretty much nothing about creating and using them though.


回答1:


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/




回答2:


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



来源:https://stackoverflow.com/questions/1535535/custom-attributes-on-actionresult

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!