Question

First, I'm sad to say I'm not sure whether this code should be in the _Layout.cshtml or somewhere in the controller. It needs to run on all pages, so I've put it in the _Layout.cshtml page.

This is for an intranet web app. What I'm attempting to do is this: if a cookie (holding the user's userid) is not found, get the windows username, run it through a class that will go into the database and get the corresponding user's username, and - if we get a user id back - make a cookie containing it. Doesn't sound too hard, but one line in particular, and various incarnations of it, is refusing to be supportive. Here's the code as a whole.

        if(!Context.Response.Cookies.AllKeys.Contains("userid")){
            var winuser = System.Web.HttpContext.Current.User.Identity.Name;
            var winuserid = myprojectname.Models.MyIntranetDataContext.getUserId(winuser).UserID();
            if (winuserid == null) {
                Response.Redirect("/someotherpage");
            } else {
                HttpCookie cookieuser = new HttpCookie("userid");
                DateTime now = DateTime.Now;
                cookieuser.Value = winuserid;
                cookieuser.Expires = now.AddMonths(1);

                Response.Cookies.Add(cookieuser);
            }
        }

Line 2 - var winuser... - appears to be the problem. In this current incarnation, I'm getting a build error: An object reference is required for the non-static field, method, or property 'myprojectname.Models.MyIntranetDataContext.getUserId(string)'

It doesn't like it when I add a .ToString to it either.

I've tried making winuser this as well: Page.User.Identity.Name;
That gave no build errors. When I attempt to Start Debugging, she blows up with this beauty of an error: 'Cannot perform runtime binding on a null reference'

Once I get the windows username, all will be well.

Really, this isn't about cookies, or even mvc to much of an extent (except maybe guidance on where to put this code - the _Layout.cshtml?). Really it's about getting the windows username, which I seem unable to do. Thanks in advance for any assistance you are able to provide.

Note, the above names aren't actual - just for example only.

Was it helpful?

Solution

If they are on the domain, couldn't you use something like the following to retrieve that information?

AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);

WindowsPrincipal principal = (WindowsPrincipal)Thread.CurrentPrincipal;
WindowsIdentity identity = (WindowsIdentity)principal.Identity;

String userName= principal.Identity.Name;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top