简体   繁体   中英

User Does Not Contain A Definition For Identity

I am attempting a simple assignment of a string to the current user ID in a service class like so:

strCurrentUserId = User.Identity.GetUserId();

//My namespace references
using HelpDesk.DAL;
using HelpDesk.Models;
using HelpDesk.ViewModels;
using System;
using Microsoft.AspNet.Identity;
using System.Security.Principal;

Where User.Identity.GetUserId is accessed via the System.Security.Principal class.

Visual Studio keeps thinking I am trying to access a model type User that I do have in my project by this is not what I am trying to call.

This exact line of code works in another class, but not this one and I don't know why.

User is a property of the Controller class which is why you cannot 'see' it from another class.

You have a couple of options:

  1. Pass the User value to your other class, for example:

     public class MyClass { public void SomeMethod(System.Security.Principal.IPrincipal user) { //do something with 'user' } } public ActionResult SomeAction() { var myClass = new MyClass(); myClass.SomeMethod(User); } 
  2. You can also retrieve the user from the HttpContext . The HttpContext class has a static method to get the current context . For example:

     var user = HttpContext.Current.User; 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM