我创建了一个自定义Authorize属性来通过远程Web API授权用户。授权后,我会收到一个带有令牌的对象,该令牌在某个特定时间内有效,用于访问更多信息,我还会获得一些基本的用户数据,如姓名,姓名,角色等等,我将其存储在会话中。
一切都运行得很好但是当我尝试使用输出缓存时,我在授权核心方法中访问的会话为空,应用程序崩溃。
如何解决这个问题,或者可能采用另一种方法来避免这种情况作为最后的手段?
授权属性
public class AuthorizeUser : AuthorizeAttribute
{
private class Http401Result : ActionResult
{
public override void ExecuteResult(ControllerContext context)
{
// Set the response code to 401.
context.HttpContext.Response.StatusCode = 401;
context.HttpContext.Response.Write("Session expired, please log in again.");
context.HttpContext.Response.End();
}
}
private readonly string[] users;
public AuthorizeUser(params string[] usrs)
{
this.users= usrs;
}
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
bool auth = false;
var loggedInUser= httpContext.Session["LoggedInUser"] as User;
if (loggedInUser != null)
auth = true;
return auth;
}
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
if (filterContext.RequestContext.HttpContext.Request.IsAjaxRequest())
filterContext.Result = new Http401Result();
else
filterContext.Result = new RedirectToRouteResult
(
new RouteValueDictionary
(
new
{
controller = "Account",
action = "Login",
}
)
);
}
}
控制器设置
[AuthorizeUser]
public class SomeController : Controller
{
[HttpPost]
[OutputCache(VaryByParam ="Year", Duration = 3600)]
public async Task<JsonResult> SomeAction(int Year){ ... }
}