Search code examples
c#asp.net-mvcip-addressclass-libraryuserid

Get UserId from class library project


Is there a way to get the UserId from a class library project? This class library project logs everything a user does and write it to a database.

But I need the UserId too which I can't get from any project except a web project. I also would need the user's ip address from the class library project.

Anyone has done this before in an asp.net-mvc project and could share it how to do it?


Solution

  • I had a similar situation in my current project, the way I did it was to pass the UserID as a parameter from the MVC project into any method I used in the class library.

    EDIT

    public int ClassLibraryMethod(your parameters, **string userId**){}
    

    Now from whatever class you are working from in your MVC project, you can call User.Identity.Name, assign it to a variable, and pass it along through your class library methods for use.

    string userId = User.Identity.Name;
    
    var lib = new ClassLibrary();
    lib.ClassLibraryMethod(your data here, userId){}
    

    This will allow you to get the userId from the MVC project through your methods.