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
452 views
in Technique[技术] by (71.8m points)

jquery - ASP.NET MVC Authorize Attribute to launch a modal?

I am working on a site that makes use of jquery modal dialogs to do various things like logging in and such.

However; we have one slight issue with the use of these.. which is we are using the [Authorize] attribute on a lot of our action methods and so what is happening is if the user is not logged in and hits a route that they need to be authorized for it shows the login page like it is suppose to but obviously this is suppose to be a modal.

Anyhow long story short, is there a way to create a custom authorize attribute that can trigger the modal instead of the actual view that makes up the login modal?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

In this case you can use a custom action filter attribute that opens a popup if the user is not authorized.
In this action filter just check if user is logged in and add a boolean value to the ViewData collection.
Aplly the attribute on the controller's action.
Then in the master page add conditional rendering of code that opens the popup.

The code for the attribute:

[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true, AllowMultiple = true)]
public class PopupAuthorizeAttribute : AuthorizeAttribute
{
    private void CacheValidateHandler(HttpContext context, object data, ref HttpValidationStatus validationStatus)
    {
        validationStatus = this.OnCacheAuthorization(new HttpContextWrapper(context));
    }

    public override void OnAuthorization(AuthorizationContext filterContext)
    {
        bool isAuthorized = false;
        if (filterContext == null)
        {
            throw new ArgumentNullException("filterContext");
        }
        if (this.AuthorizeCore(filterContext.HttpContext))
        {
            HttpCachePolicyBase cache = filterContext.HttpContext.Response.Cache;
            cache.SetProxyMaxAge(new TimeSpan(0L));
            cache.AddValidationCallback(new HttpCacheValidateHandler(this.CacheValidateHandler), null);
            isAuthorized = true;
        }

        filterContext.Controller.ViewData["OpenAuthorizationPopup"] = !isAuthorized;
    }
}

In the master page or other common view add conditional rendering:

<% if((bool)(ViewData["OpenAuthorizationPopup"] ?? true)) { %>
 ...Your code to open the popup here...
<% } %>

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

...