Access user id from repository/service #2001
-
Hi, Can anyone guide me how to access user login information from repository/service/controller ? I want to maintain created by/modified by/deleted by user id for each entities. Please guide. |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 3 replies
-
Why no response from the anyone? Without community support how this platform will be useful. |
Beta Was this translation helpful? Give feedback.
-
The services/repositories does have access to the user context as the framework can be used in any setup, with or with a web context. The simplest way to achieve this would be to subscribe to the hooks called from the different services in your application, and in that hook get the current user context from your service provider. Then you could use that information within the hook. Best regards Edit to include exampleThe easiest way (although it can be structured better for maintainability) would be to add something like this into your App.Hooks.Pages.RegisterOnBeforeSave(model =>
{
var httpContextAccessor = app.Services.GetService<IHttpContextAccessor>();
if (httpContextAccessor != null)
{
Console.WriteLine($"IDENTITY NAME IS: {httpContextAccessor.HttpContext.User.Identity.Name}");
}
}); This adds a custom method when the |
Beta Was this translation helpful? Give feedback.
-
Hi @tidyui Thank you for your response. I just implemented code and got user id by registering IHttpContextAccessor httpcontext in Dbcontext. Please correct me if its wrong way to access it. Thanks. |
Beta Was this translation helpful? Give feedback.
The services/repositories does have access to the user context as the framework can be used in any setup, with or with a web context.
The simplest way to achieve this would be to subscribe to the hooks called from the different services in your application, and in that hook get the current user context from your service provider. Then you could use that information within the hook.
Best regards
Edit to include example
The easiest way (although it can be structured better for maintainability) would be to add something like this into your
Program.cs
beforeapp.Run()
.