如果打开同一用户的两个会话,如何解决请求的 401 错误?

发布于 2025-01-13 09:23:01 字数 3196 浏览 1 评论 0原文

当我只有两个会话或多个同一用户打开时出现此错误? 补丁 https://localhost:5001/api/v1.0/UploadDownload/RemoveNotifications?targetUsername=Aymen 401 我不知道是什么问题? 该方法是关于如何使用信号器重置我所有打开的会话中的通知计数 打字稿

 public removeNotificationForUser(onlineUserModel: OnlineUserModel) {
    let targetUsername = onlineUserModel.userName;
    const url_ = `${this.baseUrlRemoveNotifications}?targetUsername=${targetUsername}`;
    const url = this.baseUrlRemoveNotifications + "/" + targetUsername;

    const body = {};
    const options = {
      headers: new HttpHeaders({
        "Content-Type": "application/json",
        "X-XSRF-TOKEN": this.cookieService.get("XSRF-TOKEN"),
      }),
    };
    return this.http.patch<any>(url_, body, options).subscribe(
      (val) => {
        console.log("PATCH call successful value returned in body", val);
      },
      (response) => {
        console.log("PATCH call in error", response);
      },
      () => {
        console.log("The PATCH observable is now completed.");
      }
    );
  }

.net核心代码

[HttpPatch("[action]/{targetUsername}")]
        [Route("removeNotifications")]
        public async Task<IActionResult> RemoveNotifications( [FromQuery] string targetUsername)
        {
            try
            {

                var sender = await _userManager.FindByNameAsync(targetUsername);
                var reciever = await _userManager.FindByNameAsync(User.Identity.Name);

                // Find The Connection
                var RecieverResetNotification= _userInfoInMemory.GetUserInfo(User.Identity.Name);
                var SenderResetNotification = _userInfoInMemory.GetUserInfo(targetUsername);

                var notificationToBeRemoved = _context.Notifications.Where(N => ((N.ReceiverId == reciever.Id) && (N.SenderId == sender.Id) && (N.IsSeen == false))).ToList();

                //Send My reset notification to the the others sessions :

                var mySessions = _context.Connections.Where(C => ((C.ConnectionID != RecieverResetNotification.ConnectionID) && (C.Username == reciever.UserName) && (C.Connected == true))).Select(MyCID => MyCID.ConnectionID).ToList();

                if (mySessions != null)
                {
                    await _hubContext.Clients.Clients(mySessions).SendAsync("MyResetNotification", RecieverResetNotification);
                }
                //Test if notificationToBeRemoved
                if (notificationToBeRemoved != null)
                { 
                notificationToBeRemoved.ForEach(NR => NR.IsSeen = true);
                _context.SaveChanges();
                }
                // My Methode to update Notification Table => change Iseen column to true //
                return Ok("Success");
            }
            catch (Exception ex)
            {
                Log.Error("An error occurred while seeding the database  {Error} {StackTrace} {InnerException} {Source}",
                   ex.Message, ex.StackTrace, ex.InnerException, ex.Source);
            }
            return BadRequest("Failed");
            
        }

I have this error when only i have two sessions or more of the same user are opened?
PATCH https://localhost:5001/api/v1.0/UploadDownload/RemoveNotifications?targetUsername=Aymen 401
I don't know what is the problem ?
the methode is about how to reset the count of notification in all my opened sessions, with signalr
typescript

 public removeNotificationForUser(onlineUserModel: OnlineUserModel) {
    let targetUsername = onlineUserModel.userName;
    const url_ = `${this.baseUrlRemoveNotifications}?targetUsername=${targetUsername}`;
    const url = this.baseUrlRemoveNotifications + "/" + targetUsername;

    const body = {};
    const options = {
      headers: new HttpHeaders({
        "Content-Type": "application/json",
        "X-XSRF-TOKEN": this.cookieService.get("XSRF-TOKEN"),
      }),
    };
    return this.http.patch<any>(url_, body, options).subscribe(
      (val) => {
        console.log("PATCH call successful value returned in body", val);
      },
      (response) => {
        console.log("PATCH call in error", response);
      },
      () => {
        console.log("The PATCH observable is now completed.");
      }
    );
  }

.net core code

[HttpPatch("[action]/{targetUsername}")]
        [Route("removeNotifications")]
        public async Task<IActionResult> RemoveNotifications( [FromQuery] string targetUsername)
        {
            try
            {

                var sender = await _userManager.FindByNameAsync(targetUsername);
                var reciever = await _userManager.FindByNameAsync(User.Identity.Name);

                // Find The Connection
                var RecieverResetNotification= _userInfoInMemory.GetUserInfo(User.Identity.Name);
                var SenderResetNotification = _userInfoInMemory.GetUserInfo(targetUsername);

                var notificationToBeRemoved = _context.Notifications.Where(N => ((N.ReceiverId == reciever.Id) && (N.SenderId == sender.Id) && (N.IsSeen == false))).ToList();

                //Send My reset notification to the the others sessions :

                var mySessions = _context.Connections.Where(C => ((C.ConnectionID != RecieverResetNotification.ConnectionID) && (C.Username == reciever.UserName) && (C.Connected == true))).Select(MyCID => MyCID.ConnectionID).ToList();

                if (mySessions != null)
                {
                    await _hubContext.Clients.Clients(mySessions).SendAsync("MyResetNotification", RecieverResetNotification);
                }
                //Test if notificationToBeRemoved
                if (notificationToBeRemoved != null)
                { 
                notificationToBeRemoved.ForEach(NR => NR.IsSeen = true);
                _context.SaveChanges();
                }
                // My Methode to update Notification Table => change Iseen column to true //
                return Ok("Success");
            }
            catch (Exception ex)
            {
                Log.Error("An error occurred while seeding the database  {Error} {StackTrace} {InnerException} {Source}",
                   ex.Message, ex.StackTrace, ex.InnerException, ex.Source);
            }
            return BadRequest("Failed");
            
        }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文