c# - AuthorizeAttribute 和参数

标签 c# asp.net-mvc

我的应用程序中有一个自定义的 AuthorizeAttribute,它接受一个输入参数 bool UserIsOnline。此参数用于增加一个表字段,该字段包含有关上次用户交互时间的信息,即对于在后台执行的 ajax 请求,我提供一个 false,对于常规请求或用户发起的请求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;
  }
}

最佳答案

您可以完全跳过参数并使用 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
    }

关于c# - AuthorizeAttribute 和参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12194459/

相关文章:

c# - 当发票不包含任何项目时,Linq 返回 null

c# - 使用 SAPI 将语音转换为文本

c# - 如何抓取 JavaScript WebBrowser 更新的内容

c# - 如何增加行列式进度条的粗细?

jquery - 显示错误/警告的最佳方法是在MVC中使其显示或传递自定义属性?

c# - 格式化逻辑属于 MVC 的什么地方?

c# - 使用和不使用私有(private)访问器的单元测试

asp.net-mvc - 在asp mvc中使用json上传图像

asp.net-mvc - 如何将多个默认值添加到 ASP.NET MVC3 中的 SelectList

asp.net-mvc - 使用 msbuild 检查编译时 mvc View