簡體   English   中英

使用ASP.net核心Identity MVC登錄用戶的日志IP

[英]Log IP of signed in user with ASP.net core Identity MVC

我想要實現的目標:

保存用戶的IP,將特定操作/控制器命中到我的數據庫。 此外,由於此過程需要花費大量時間,因此如果在后台線程或類似操作上執行它將會很好。

到目前為止我嘗試了什么:

創建一個如下所示的CustomAuthorizeAttribute:

    public class LoggedAuthorizeAttribute : TypeFilterAttribute
    {
        public LoggedAuthorizeAttribute() : base(typeof(LoggedAuthorizeFilter))
        {
        }
    }

    public class LoggedAuthorizeFilter : IAuthorizationFilter
    {
        private readonly UserManager<User> _userManager;

        public LoggedAuthorizeFilter(UserManager<User> userManager)
        {
            _userManager = userManager;
        }

        public async void OnAuthorization(AuthorizationFilterContext context)
        {
            if (!context.HttpContext.User.Identity.IsAuthenticated)
                return;

            var user = await _userManager.GetUserAsync(context.HttpContext.User);

            var remoteIpAddress = context.HttpContext.Connection.RemoteIpAddress;

            user.UserLogins.Add(new UserLogin
                {LoggedInOn = DateTimeOffset.UtcNow, LoggedInFrom = remoteIpAddress});

            await _userManager.UpdateAsync(user);
        }
    }

此解決方案的問題:

  1. 當請求命中標記有此屬性的操作時,請求將花費大約1-2秒直到它實際處理該操作。
  2. UserManager由依賴注入檢索,但我也在我的一些操作中訪問UserManager實例,這導致InvalidOperationException告知A second operation started on this context before a previous operation completed. This is usually caused by different threads using the same instance of DbContext, however instance members are not guaranteed to be thread safe. This could also be caused by a nested query being evaluated on the client, if this is the case rewrite the query avoiding nested invocations. A second operation started on this context before a previous operation completed. This is usually caused by different threads using the same instance of DbContext, however instance members are not guaranteed to be thread safe. This could also be caused by a nested query being evaluated on the client, if this is the case rewrite the query avoiding nested invocations.

任何形式的幫助表示贊賞。

更新

正如Kirk Larkin所建議實現IAsyncActionFilter而修復了我遇到的第二個問題。 但是,如果這是一個正確的選擇,我將如何在后台線程或類似的東西中執行此操作。

所以我修復了我的第一個問題,使用了ConcurrentQueue ,它在后台線程上將其項目出列。 我在這篇博文中找到了這個解決方案。 它只需要稍微修改一下就可以解決這個問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM