在ASP.NET核心中运行控制器问题之前,请检查会话



因此,在控制器中运行任何操作之前,我想检查会话是否存在。我找到了这些解决方案链接1、链接2,并尝试实现它们。这是我的SessionAuthorize类,这里一切似乎都很好:

public class SessionAuthorize : ActionFilterAttribute
{
private readonly SessionManager _sessionManager;
public SessionAuthorize(SessionManager sessionManager)
{
_sessionManager = sessionManager;
}
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (!_sessionManager.IsLoggedIn)
{
filterContext.Result = new RedirectToRouteResult(
new RouteValueDictionary {
{ "Controller", "Home" },
{ "Action", "Login" }
});
}
}
}

现在,问题是当我试图在控制器中调用它时。所以我应该通过添加[SessionAuthorize]属性来调用,如下所示:

[SessionAuthorize]
public class AccountController : Controller
{
//code
}

但它给了我一个错误,我没有正确地称呼它。我认为这与我在SessionAuthorize中用于访问会话的依赖项注入有关。但我现在不知道该怎么称呼它。

错误消息为:

'没有给出与所需形式相对应的参数的参数"sessionManager"'SessionAuthorize.SessionAuthorize(SessionManager('

所以我想知道我应该如何在我的控制器中使用它

如果您想避免服务定位器模式,可以通过TypeFilter的构造函数注入来使用DI。

在控制器中尝试使用

[TypeFilter(typeof(SessionAuthorize)]

并且您的ActionFilterAttribute不再需要访问服务提供商实例。

最新更新