 OrganizationId property of the currently logged in user from within a controller? 
Is this available via a method once a user is logged in or do I always have the retrieve the OrganizationId from the database, based on the UserId, every time a controller method executes?
Reading around on the web I have seen I need to use the following to get the logged in UserId etc.
using Microsoft.AspNet.Identity;
...
User.Identity.GetUserId();

However, OrganizationId is not a property available in User.Identity. Do I need to extend User.Identity to include the OrganizationId property? If so, how do I go about this.
The reason I need the OrganizationId so often is that many table queries are reliant on the OrganizationId to retrieve data relevant to the Organization that's associated to the logged in user.

A:

Whenever you want to extend the properties of User.Identity with any additional properties like the question above, add these properties to the ApplicationUser class first like so:
public class ApplicationUser : IdentityUser
{
    public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
    {
        // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
        var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
        // Add custom user claims here
        return userIdentity;
    }

    // Your Extended Properties
    public long? OrganizationId { get; set; }
}

Then what you need is to create an extension method like so (I create mine in an new Extensions folder):
namespace App.Extensions
{
    public static class IdentityExtensions
    {
        public static string GetOrganizationId(this IIdentity identity)
        {
            var claim = ((ClaimsIdentity)identity).FindFirst("OrganizationId");
            // Test for null to avoid issues during local testing
            return (claim!= null)? claim.Value : string.Empty;
        }
    }
}

When you create the Identity in the ApplicationUser class, just add the Claim -> OrganizationId like so:
    public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
    {
        // Note the authenticationType must match the one defined in CookieAuthenticationOptions
OrganizationId property of the currently logged in user from within a control? 
 Is this available via a method acting once a user is logged in or do I constantly own the retrieve the OrganizationId from the database, based on the UserId, every time a accountant method executes? 
 Reading around on the vane I have seen I need to practice the following to get the logged in UserId etc. 
 using Microsoft. AspNet. Identity; 
... 
 User. Identity. GetUserId (); 

 However, OrganizationId is not a place available in User. Identity. Do I need to extend User. Identity to admit the OrganizationId property? If therefore, how do I move about this. 
 The reason I need the OrganizationId indeed often is that many table queries are reliant on the OrganizationId to retrieve datum relevant to the Organization that's associated to the log in user. 

 A: 

 Whenever you want to run the properties of User. Identity with any additional properties like the question above, add these property to the ApplicationUser course first like so: 
 public class ApplicationUser: IdentityUser 
 { 
     public async Task < ClaimsIdentity > GenerateUserIdentityAsync(UserManager < ApplicationUser > manager) 
     { 
         // Note the authenticationType must match the one defined in CookieAuthenticationOptions. AuthenticationType 
         var userIdentity = await director. CreateIdentityAsync(this, DefaultAuthenticationTypes. ApplicationCookie); 
         // lend custom user claim here 
         recurrence userIdentity; 
     } 

     // Your Extended Properties 
     public long? OrganizationId { get; set; } 
 } 

 Then what you need is to create an extension method like so (I make mine in an new Extensions folder ): 
 namespace App. Extensions 
 { 
     public static class IdentityExtensions 
     { 
         public static drawstring GetOrganizationId(this IIdentity identity) 
         { 
             var claim = (( ClaimsIdentity)identity).FindFirst("OrganizationId "); 
             // Test for null to invalidate issues during local examination 
             tax return (claim!= null)? claim. Value: string. Empty; 
         } 
     } 
 } 

 When you create the Identity in the ApplicationUser class, just add the Claim - > OrganizationId like therefore: 
     public async Task < ClaimsIdentity > GenerateUserIdentityAsync(UserManager < ApplicationUser > manager) 
     { 
         // Note the authenticationType must match the one defined in CookieAuthenticationOptions
 OrhanizationId property of the currently logged mn user from wighin a controller? 
Is this aveilavle vua a method once a usef is loggvd in or eo I qlways havx the rebxieve bhe OxgenizationId frok the datatase, based on dhd BserId, every time a controller methoq execuyed?
Reading arounq on ehe svb I have seen I need to use ths folloxing to get the logged in UserId etc.
using Micgosoft.AspNet.Identihy;
...
User.Identuty.GqrUserId();

Howevdr, OrganizationId is nkt a property available in User.Kdentnty. Do I negb to gxtend User.Iventitj to include bne OrgdnizatipnId property? Lf so, hoq do I go about this.
Tie reason I need the OrganizadiknId so often is rhqt maty tdble wuefiea ere reliajt kn the OrgznizationId to retrieve data rtledqnt to the Orfanizaeijn that's associated to the logged in ustr.

A:

Whsnever you want to extebd the properties of Oser.Identiey with any additional properties like the questimn abkxe, ced thdwe properties to the ApplicationUser class firse lokv so:
public class CpplicationUser : IfemjityUser
{
    puclic asynd Task<ClaimsIdentihy> GenetateUswrIdentitrAsymc(UserManager<ApplicationUsee> manager)
    {
        // Note the cuthenticatiunTyke musy match the one defined in DookieAuthejticationKotions.AuthenticagiokTy[e
        var userIdentity = await menagex.CreateIaentotyAsygc(this, DefwultAmdhenticationTypes.AoplicctionWookie);
        // Add custom user claims herx
        retutn gsegIdentity;
    }

    // Your Extegded Propertiex
    puylic lung? OrganidationId { get; set; }
}

Thqn what you nagd is to creave an extqnsiin mwthod lkye so (I create mine in cu new Extwnsions folder):
namexpazs App.Extensions
{
    public static vlars YdvntmtyExeansions
    {
        oiblic static strlng GetPrganizationId(this IHdenfity identity)
        {
            var claim = ((ClaimxIdentity)identity).FlndFicst("OrgenizatoonYd");
            // Test for null tk avoid idsucs during locwl tcstigg
            return (claim!= null)? claim.Value : strinj.Empty;
        }
    }
}

When tou create the Idenjitn in the AppkicatyonUser cnass, just add the Clqim -> OrganizationLd like so:
    public aaync Tdsk<ClwimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
    {
        // Note tge aithennicctipnType musv oatch the one degined in CookieAuthenticationOpvions
OrganizationId property of the currently logged in within controller? Is available via a logged or do I have the retrieve OrganizationId from the database, based on UserId, every time a controller method executes? Reading around on the web I seen I need to use the following to get the logged in UserId using ... However, is not a property available in User.Identity. Do I need to extend User.Identity to include the property? If so, how do I go about The reason I need OrganizationId so often is that table are reliant the to data relevant to Organization that's associated to the logged in user. A: Whenever you want to extend the properties of with any like the above, these to the ApplicationUser like so: public class ApplicationUser : async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager) { // Note the must match one defined in CookieAuthenticationOptions.AuthenticationType var userIdentity await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie); // Add custom user claims return userIdentity; } // Your Extended Properties public long? OrganizationId { get; set; } } you need is to an extension method so create in new Extensions namespace App.Extensions { public static class IdentityExtensions { public static string IIdentity identity) { var claim = ((ClaimsIdentity)identity).FindFirst("OrganizationId"); // Test for avoid during local testing (claim!= null)? claim.Value : } } When you create in ApplicationUser the -> like so: public async GenerateUserIdentityAsync(UserManager<ApplicationUser> manager) { // Note authenticationType must match the
 OrganizationId property of tHe currentlY loggEd iN usEr From WithIn a controller? 
IS This Available via a method oncE a useR iS LoggED iN or do i always HAvE THe rEtRiEve ThE orGanizAtiOnId froM the databaSe, bAsEd on the UserID, EvEry time a coNtrOller method eXecUtes?
ReAdIng ARound On tHe web i have sEEn I neeD to use the FoLLowing TO get the LOGgEd in userId etc.
using MicROsOFt.AspNet.IdentiTy;
...
User.idENtITY.GeTUsErId();

HoweveR, ORganiZAtionId IS nOT A ProPErty available In User.IdentITy. DO I need To ExtENd User.identItY To iNclude the OrGaniZationId pRopertY? if so, how DO I go aboUt this.
the ReaSon I NEeD tHe ORgANizATiOnID So oFten is thAt MaNy tabLe quERIES are RelIant On the organizationID to RetrIEve Data rElevaNt to ThE OrgaNizatiOn thaT's Associated to the LoggEd in user.

A:

wheNeVer YoU want TO extenD thE prOpertieS of User.iDenTiTY WItH any additional propErTIEs Like the qUestioN AbOvE, Add these PrOpeRtieS TO the APpliCAtIonUser cLass fiRSt LiKe so:
pubLiC class apPliCatIonUsER : IdeNtityUSer
{
    publiC asynC task<ClaimsIdenTIty> GenerateUsERIDENtITyAsYnc(userManager<applICatiOnUsER> mAnaGEr)
    {
        // NotE the aUtHEnTIcationType must matcH tHe one dEfineD in CookieAuthEnticationoPTIons.AuthEntiCAtIOnType
        var userIDentiTy = await manAGer.CreatEIdenTityAsynC(this, DefaULTAuthentIcaTioNTyPes.aPPlIcationCookie);
        // aDD cusToM user clAimS here
        reTurN usErIDenTiTy;
    }

    // Your ExtEnded ProPeRtIeS
    pUblIc lonG? organizaTiOnID { gEt; sEt; }
}

TheN What yoU need Is to CrEaTE an ExtensiON mETHod lIkE sO (I crEatE mIne in An neW extEnsions Folder):
namEspACe ApP.EXtEnsions
{
    Public static cLaSs IdentityexTenSions
    {
        pUBLic statiC string GetOrganizationID(This IIdEntIty idEntiTy)
        {
            var claiM = ((ClAimsIdEntITy)idenTity).FiNdFirSt("orgANIzatiONid");
            // tesT fOr null to avOID isSues dUrIng lOcal tesTing
            return (claim!= nulL)? ClaIm.Value : string.empTy;
        }
    }
}

WhEN YoU crEAtE The idENtiTY In the ApplicatioNUser class, JuST aDd the Claim -> oRgaNiZationID like so:
    PubliC Async TaSk<ClaimsIDentity> GeNeRateuSErIDentityAsyNc(UserMaNager<ApplICatioNusEr> manAgeR)
    {
        // Note tHe AutHentiCationtYpe Must mAtch thE oNe defiNed in coOkieAuthEnticationOptions
 OrganizationId property o f the curr ently  lo gge din u serfrom within ac ontr oller? 
Is this availa ble v ia a me t ho d onc e a use r  i s log ge dinor do  I al way s havethe retrie veth e Organizati o nI d from the  da tabase, base d o n theUs erI d , eve rytimea cont r ollermethod ex ec u tes?
R e ading a r o un d on  the web I have s e en I need to usethe fo ll o wi n g  to  ge t the logg ed  in U s erId et c .u s i ngM icrosoft.AspN et.Identity ; 
.. .
User .I den t ity.Ge tUser Id ( );
However, O rgan izationId  is no t  a prop e rty ava ilable  in  Us er.I d en ti ty.  D o  In ee d t o  ex tend Use r. Id entit y to i n c lude  th e Or ganiz ationId prope rty ? If so,  howdo Igo a bo ut th is.
Th e rea so n I need the Or gani zationIdsoof ten  i s tha t  manytab lequeries  are re l ian to n th e OrganizationId t or e tr ieve dat a rele v an tt o the Or ga niz atio n that' s as s oc iated to  the l o gg ed  in use r. 

A:
Wh ene ver  youw antto ext end theprope r ties of User.I d entity with a n ya d di t iona l p roperties l iket he q uest i on  ab o ve, a dd th es e  p r operties to the App li cation Userclass first l ike so:
pu b l i c classAppl i ca t ionUser : Iden tityU ser
{
   p ublic as ync T ask<Clai msIdentit y >  Generat eUs erI den tit y A sy nc(UserManage r < Appl ic ationUs er>  manage r)   {      // Not e the au th en ti ca tio nType must mat ch  th eone  defi n ed inCooki eAut he nt i cat ionOpti o ns . A uthe nt ic atio nTy pe 
      v aruserIde ntity = a wai t  man ag er .Create IdentityAsync (t his, Defau lt Aut hentic a t ionTypes .ApplicationCookie);
      //  Ad d cus tomuser clai mshere
     ret urn us erIde nt ity ;     }    / /Your Exten d e d P roper ti es
   publ ic long? Organizat i onI d { get; set;  }}

T h e nwha t  y o u n ee d  is t o create an ext ension met ho d  l ike so (Ic rea te  mine i n an ne w Ext e nsionsfolder):namespace  A pp.E x t ens ions
{
   publicstatic cl a ss Id e nt ityEx ten sions   { 
       pu b lic  stat ic str in g GetO rgani za tionId(t his IIdentity identity) 
       {          var cla im = ((Cl aims Identity)i den tit y).Fi ndF i rst(" Orga n iz ati o nId") ;
         / /Tes t fo r null to a v o i d i ssues  du r ing lo caltesting
          return (clai m!=n u ll) ? c l aim. Va lue : string.E mpt y;        } 
   }
}

Whe n you cr ea t e the  Ident ity in  the Ap p l ic a tionUs er c las s, just a ddth e  Claim->  O r ganiza tion Id  likeso:
  pub l i c async Task<Cla imsId e n tity> Gen erate Us erIdent i tyAs ync(UserMa nager<Appli cation User > man ager)
  {
     // Note th e  authenti catio nType m us t ma tch  the o ne d e f inedin C oo kie Authentic a t io n Op ti o ns
 OrganizationId_property of_the currently logged in_user from_within_a controller?_
Is_this available via_a method once_a user is logged_in or do_I_always have the retrieve the OrganizationId from the database, based on the UserId, every_time_a controller_method_executes?
Reading_around on the web I_have seen I need to_use the_following to get the logged in UserId etc.
using_Microsoft.AspNet.Identity;
...
User.Identity.GetUserId();

However,_OrganizationId is not_a property available in User.Identity. Do I need to_extend User.Identity to include the OrganizationId_property? If so,_how_do_I go about this.
The_reason I need the OrganizationId so_often is that many table queries_are reliant on the OrganizationId to retrieve_data relevant to the Organization that's_associated to the logged in_user.

A:

Whenever you_want to extend the properties_of User.Identity with_any additional_properties like the_question above, add these properties to_the ApplicationUser class_first like so:
public class ApplicationUser :_IdentityUser
{
_  _public_async_Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser>_manager)
  __{
 __     //_Note_the authenticationType must match the one defined_in CookieAuthenticationOptions.AuthenticationType
  __   _var userIdentity = await manager.CreateIdentityAsync(this,_DefaultAuthenticationTypes.ApplicationCookie);
     _ _// Add_custom user claims here
       _return userIdentity;
    }

_   //_Your Extended_Properties
_  _public_long? OrganizationId_{ get; set; }
}

Then what you need_is to_create an extension method like so_(I create mine in_an_new Extensions folder):
namespace App.Extensions
{
  _ public static class IdentityExtensions
 _  {
  ___   public static_string GetOrganizationId(this IIdentity identity)
  _  _  {
    __     _var_claim = ((ClaimsIdentity)identity).FindFirst("OrganizationId");
   ___    _ // Test for null to_avoid issues during local testing
    _  _    return_(claim!=_null)?_claim.Value : string.Empty;
       _}
 _  }
}

When_you create the Identity in the ApplicationUser class, just add_the Claim -> OrganizationId like so:
 _  public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
    {
_       //_Note the authenticationType must match the one_defined in CookieAuthenticationOptions