【问题标题】:Custom authentication in MVC, filterContext is nullMVC中的自定义认证,filterContext为null
【发布时间】:2019-08-13 05:39:06
【问题描述】:

在一个网络应用程序中,我试图引入操作属性以在我的操作中添加身份验证。现在,我在每个操作中单独检查有效会话。

我创建了一个使用 AuthorizeAttribute 的自定义属性:

public class BaseAuthAttribute : AuthorizeAttribute

我用

装饰我的动作
[BaseAuth]

现在在 BaseAuthAttribute 我有这段代码

public override void OnAuthorization(AuthorizationContext filterContext)
{
    var session = new BusinessLayer.PortalUser(filterContext.HttpContext.Request.Cookies["appname"]);
    if(!session.IsAuthorized()
    {
        filterContext.Result = new RedirectToRouteResult(
                new RouteValueDictionary { { "controller", "Home" }, { "action", "Login" } });
    }
}

但是当我没有活动会话时,Result = new 行会爆炸,对象实例对对象没有意义。

我没有使用 ASP.Net 内置的身份验证,而是通过自定义来确定是否存在会话/用户。那么 filterContext 是否只能在您使用 AP.Net 成员资格类时使用?

如果他们的会话已过期/不存在,或者确实具有正确的权限,我需要重定向到视图

【问题讨论】:

    标签: c# asp.net-mvc


    【解决方案1】:

    我为我设计了一个自定义授权属性,用于检查用户会话,如果过期则重定向到登录页面。您可以在此查看会话值。

    public class SessionExpireAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            // check  sessions here
            if (HttpContext.Current.Session["employeeid"] == null)
            {
                filterContext.Result = new RedirectResult("~/Account/Login");
                return;
            }
            base.OnActionExecuting(filterContext);
        }
    }
    

    但是您需要将此属性与 Authorize 属性一起使用,因为它只是检查会话值。

    更新

    如果您没有使用 ASP.NET 会员资格提供程序,请试试这个

    public class BaseAuthAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            var session = new BusinessLayer.PortalUser(filterContext.HttpContext.Request.Cookies["appname"]);
            if (!session.IsAuthorized()
            {
                filterContext.Result = new RedirectResult("~/Account/Login");
                return;
            }
            base.OnActionExecuting(filterContext);
        }
    }
    

    【讨论】:

    • 当你说我需要将此属性与 Authorize 一起使用时,你的意思是我需要两者吗?
    • 是的,因为这个属性只是检查会话值。您需要使用 Authorize 属性来授权用户
    • 但是 [Authorize] 是针对 ASP.Net 会员的东西 - 我需要自定义验证,所以我认为我不需要 [Authorize]
    • 好的。我知道了。但是,如果您不使用 Asp.Net 成员资格,则不能使用从 AuthorizeAttribute 继承的 CustomAuthorize 属性。但是,您可以使用我提供的自定义属性并根据您的需要进行更改。
    • @andrewb 我已根据您的要求使用自定义授权属性更新了我的答案。
    猜你喜欢
    • 2018-10-30
    • 1970-01-01
    • 1970-01-01
    • 2016-06-22
    • 1970-01-01
    • 2015-01-01
    • 2012-09-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多