我对ASP.NET MVC缓存和授权感到困惑,并且急需一些澄清.
我的自制授权属性继承自AuthorizeAttribute.它的重写AuthorizeCore方法每次都会运行,即使我[OutputCache]在控制器操作上设置了一个属性.我明白那一部分.
现在,对我来说这个问题:现在当我实际执行输出缓存并且从缓存中提供页面时,每次AuthorizeCore都会失败.原因是当缓存请求时,httpContext.Session提供的AuthorizeCore是null!?这是一些简化的代码:
protected override bool AuthorizeCore(HttpContextBase httpContext) {
return (Session["userId"] != null)
}
Run Code Online (Sandbox Code Playgroud)
所以如果httpContext.Session是null,这显然每次都失败了.我需要访问会话,我还能如何检查请求是否被授权?这没有任何意义 - 如果这是它应该如何,那么我永远不能在ASP.NET MVC中使用缓存页面和身份验证.救命?
我有这个想要调用的动作过滤器,我已经在 Startup.cs 中声明了它。但是,当我在班级上方调用它时,出现此错误:
LogUserNameFilter 不是属性类
我不确定我错过了什么。
public class LogUserNameFilter : IActionFilter
{
private readonly RequestDelegate next;
public LogUserNameFilter(RequestDelegate next)
{
this.next = next;
}
public void OnActionExecuted(ActionExecutedContext context)
{
throw new NotImplementedException();
}
public void OnActionExecuting(ActionExecutingContext context)
{
LogContext.PushProperty("UserName", context.HttpContext.User.Identity.Name);
}
}
Run Code Online (Sandbox Code Playgroud)
启动文件
services.AddScoped<LogUserNameFilter>();
Run Code Online (Sandbox Code Playgroud)
类声明
[LogUserNameFilter]
public class HomeController : Controller{
}
Run Code Online (Sandbox Code Playgroud)