Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
329 views
in Technique[技术] by (71.8m points)

c# - Is it possible to override the default behavior of [Authorize] in ASP.NET MVC?

I wondered if/how I can override the default [Authorize] behavior in ASP.NET MVC. I know that I can create a new Action Filter, make my own attribute and so forth; I am merely interested if I can simply change the [Authorize] behavior and replace its workings with my own code?

Edit: Guys and Girls. I appreciate your input but as I wrote, I am not looking to introduce a new [XYZAuthorize] Attribute. I'm aware of how to do this. I want to keep the [Authorize] notation but just change how it works.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can subclass the AuthorizeAttribute filter and put your own logic inside it.

Let's see an example. Let's say you want to always authorize local connections. However, if it is a remote connection, you would like to keep the usual authorization logic.

You could do something like:

public class LocalPermittedAuthorizeAttribute : AuthorizeAttribute
{
    protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            return (httpContext.Request.IsLocal || base.AuthorizeCore(httpContext)));
        }
}

Or you could always authorize a certain remote address (your machine, for example).

That's it!

Edit: forgot to mention, you will use it the same as you would use the AuthorizeAttribute filter:

class MyController : Controller
{
    [LocalPermittedAuthorize]
    public ActionResult Fire()
    {
        Missile.Fire(Datetime.Now);
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...