Get current user ID?

Topics: Troubleshooting, Writing modules
Feb 12, 2012 at 7:36 PM

Hi!,

I want to get the current user ID and found some post saying you can use WorkContext.CurrentUser.ID, but in my controller i can´t find a way to instance the WorkContext, am i missing some references in my project? Someone that have any ideas?

Feb 12, 2012 at 7:41 PM

Take in a parameter of type IOrchardServices in your controller's constructor. Access WorkContext as a property of the IOrchardServices instance.

    public class MyController : Controller
    {
        private readonly IOrchardServices _orchardServices;

        public MyController(IOrchardServices orchardServices) {
                _orchardServices = orchardServices; 
        }

        public ActionResult MyAction()
        {
                _orchardServices.WorkContext.CurrentUser;
        }
    }

Feb 12, 2012 at 8:59 PM

yea i know the syntax of the code, but i can´t  instance IOrchardServices because i probably miss some reference in my project. but i can´t figure out what iam missing. I got references for Orchard.Core and Orchard.Framework? 

Feb 12, 2012 at 9:04 PM

I'm not sure what you mean by "can't instance IOchardServices". Try adding references to Orchard.Core, Orchard.Framework, and Orchard.Users. 

Here's a list of all namespaces I'm importing in the controller where I'm using code similar to what I posted above. You can clean it up by removing the ones you don't need: 

using Orchard;
using Orchard.Core; 
using Orchard.ContentManagement;
using Orchard.DisplayManagement;
using Orchard.Localization;
using Orchard.Logging;
using Orchard.Mvc;
using Orchard.Mvc.Extensions;
using Orchard.Security;
using Orchard.Users.Events;
using Orchard.Users.Models;
using Orchard.Users.Services;

Feb 13, 2012 at 6:52 AM

Hi!,

thx for the help TheMonarch!, it was exactly what is was meaning,