Global variable on asp.net

I want to declare a variable, as shown below, for use on multiple pages of my site. I guess, rather than declaring it once per page, can I do it globally? I tried this in the class (app_code folder) and on the global.asax page, but my code does not seem to be able to find it. Maybe I'm wrong? Code below ...

Dim myUser As MembershipUser = Membership.GetUser()

Basically, as it stands, my pages cannot find the variable "myUser". Any help is much appreciated! Thanks

+3
source share
4 answers

Create a class / struct and add a static

namespace MyApp
{
    public class Variables
    {
        public static User MembershipUser
        {
            get { return Membership.GetUser(); }
        }
    }
}

Then you can access the value / property:

MyApp.Variables.MembershipUser

GetUser() "Username", :

Hello <%=MyApp.Variables.MembershipUser.Username%>

VB.NET:

 Namespace MyApp
    Public Class Variables
        Public Shared ReadOnly Property MembershipUser() As User
            Get
                Return Membership.GetUser()
            End Get
        End Property
    End Class
End Namespace
+2

Session Application , "".

Session, , Application, .

+3

This can be in the base class of the page or in the extension method to System.Web.UI.Page

public  static MembershipUser GetMembershipUser(this System.Web.UI.Page page)
{
    return Membership.GetUser();
}
0
source

@ stian.net I have the following - it works exactly the way I want. Would you say this is the right way to do this?

Public Class Variables
Public Shared ReadOnly Property myUser As MembershipUser
    Get
        Return Membership.GetUser()
    End Get
End Property
End Class
0
source

Source: https://habr.com/ru/post/1781644/


All Articles