ASP.NET MVC 授权属性启动模式? [英] ASP.NET MVC Authorize Attribute to launch a modal?

查看:14
本文介绍了ASP.NET MVC 授权属性启动模式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个网站,该网站利用 jquery 模式对话框来执行各种操作,例如登录等.

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

但是;我们在使用这些方面有一个小问题.. 我们在很多操作方法上都使用了 [Authorize] 属性,所以如果用户没有登录并点击了他们需要的路线,就会发生这种情况被授权显示登录页面,但显然这应该是一个模式.

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?

推荐答案

在这种情况下,您可以使用自定义操作过滤器属性,如果用户未获得授权,则该属性会打开一个弹出窗口.
在此操作过滤器中,只需检查用户是否已登录并向 ViewData 集合添加一个布尔值.
将属性应用于控制器的操作.
然后在母版页中添加打开弹出窗口的代码的条件渲染.

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.

属性代码:

[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...
<% } %>

这篇关于ASP.NET MVC 授权属性启动模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆