我的应用程序中有一个自定义AuthorizeAttribute,它接受一个输入参数bool UserIsOnline
。此参数用于增加一个表字段,该表字段包含有关上次用户交互时间的信息,即对于我提供false
幕后执行的ajax请求以及常规请求或用户启动的ajax请求,一个true
值。
这大部分时间都有效,但并非总是如此。 I've read that AuthorizeAttribute
不是线程安全的,这让我想知道这个UserIsOnline
参数是否错误,因为它在被处理之前被另一个进程修改。我该如何解决这个问题?我不应该使用AuthorizeAttribute进行此操作吗?
public class MyAuthorizeAttribute : AuthorizeAttribute
{
private MyMembershipProvider _provider = new MyMembershipProvider(); // this class is thread-safe
private bool _userIsOnline = true;
public bool UserIsOnline { get { return _userIsOnline; } set { _userIsOnline = value; } }
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
if (httpContext == null)
{
throw new ArgumentNullException("httpContext");
}
// Check if user is authenticated
IPrincipal user = httpContext.User;
if (!user.Identity.IsAuthenticated)
{
return false;
}
// Check that the user still exists in database
MyMembershipUser myUser = (MyMembershipUser)_provider.GetUser(user.Identity.Name, _userIsOnline);
if (myUser == null)
{
// User does not exist anymore, remove browser cookie
System.Web.Security.FormsAuthentication.SignOut();
return false;
}
return true;
}
}
答案 0 :(得分:1)
您可以完全跳过参数并使用httpContext.Request.IsAjaxRequest
public class MyAuthorizeAttribute : AuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
if (httpContext == null)
{
throw new ArgumentNullException("httpContext");
}
// Check if user is authenticated
IPrincipal user = httpContext.User;
if (!user.Identity.IsAuthenticated)
{
return false;
}
if (!httpContext.Request.IsAjaxRequest())
{
// do your thing in the DB
}