gpt4 book ai didi

c# - MVC自定义认证,filterContext为null

转载 作者:太空宇宙 更新时间:2023-11-03 11:59:59 25 4
gpt4 key购买 nike

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

我创建了一个使用 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" } });
}
}

但是当我没有事件 session 时,Result = new 行会爆炸,对象实例无法感知。

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

如果他们的 session 已过期/不存在,或者他们确实拥有正确的权限,我需要重定向到一个 View

最佳答案

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

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);
}
}

但是您需要将此属性与授权属性一起使用,因为它只是检查 session 值。

已更新

如果您没有使用 ASP.NET 成员(member)提供程序,请试试这个

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);
}
}

关于c# - MVC自定义认证,filterContext为null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57471694/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com