c# - Can we extend HttpContext.User.Identity to store more data in asp.net? -


i using asp.net identity. create default asp.net mvc application implement user identity. application use httpcontext.user.identity retrieve user id , user name :

string id = httpcontext.user.identity.getuserid(); string name = httpcontext.user.identity.name; 

i able customize aspnetusers table. add properties table want able retrieve these properties httpcontext.user. possible ? if possible, how can ?

you can use claims purpose. default mvc application has method on class representing users in system called generateuseridentityasync. inside method there comment saying // add custom user claims here. can add additional information user here.

for example, suppose wanted add favourite colour. can by

public async task<claimsidentity> generateuseridentityasync(usermanager<applicationuser> manager) {     // note authenticationtype must match 1 defined in cookieauthenticationoptions.authenticationtype     var useridentity = await manager.createidentityasync(this, defaultauthenticationtypes.applicationcookie);     // add custom user claims here     useridentity.addclaim(new claim("favcolour", "red"));     return useridentity; } 

inside controller can access claim data casting user.identity claimsidentity (which in system.security.claims) follows

public actionresult index() {     var favouritecolour = "";     var claimsidentity = user.identity claimsidentity;     if (claimsidentity != null)     {         var claim = claimsidentity.findfirst("favcolour");         if (claim != null && !string.isnullorempty(claim.value))         {             favouritecolour = claim.value;         }     }      // todo: value , pass view model...      return view(); } 

claims because stored in cookies once you've loaded , populated them once on server, don't need hit database again , again @ information.


Comments

Popular posts from this blog

dns - How To Use Custom Nameserver On Free Cloudflare? -

qt - Passing a QObject to an Script function with QJSEngine? -

c# - Web API response xml language -