在C#中设置类以初始化公共变量的正确方法是什么?

时间:2018-10-18 14:59:42

标签: c# web-services

我已经在c#的底部创建了该类。 Webservices引用此类来确定用户访问权限,例如:

[WebMethod]
public List<FAFSA> getFAFSA(string pageID)
{
    formValues fv = new formValues();
    string personID = fv.personID;
    List<FAFSA> lf = new List<FAFSA>();

    if (fv.secBlur == "no_secBlur")
    {
        FAFSA f = new FAFSA();
        f.fafsaCheck = "0";
        lf.Add(f);
    }

    ...
}

我正在尝试添加两个变量fafsa和staff。方法getSecBlur()从secBlur,fafsa和staff返回我数据库中的所有三个值。那么,如何设置此类,使SecBlur方法仅被调用一次,却填充我的所有三个变量,以便可以在Web服务调用中使用它们?它不能像现在那样工作,因为它说fafsa和staff必须是静态的,但是如果我将它们设为静态,则在webservices中它说必须使用实例引用来访问成员。

很抱歉,如果措辞不好,但我对此并不陌生,仍在尝试学习...

public class formValues : System.Web.Services.WebService
{
    public string userName = getUserName();
    public string firstName = getFirstName();
    public string personID = getPersonID();
    public int fafsa = 0;
    public int staff = 0;
    public string secBlur = getSecBlur();

    private static string getUserDataString(int ix)
    {
        string retValue = "";

        if (HttpContext.Current.Request.IsAuthenticated)
        {
            HttpCookie authCookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];

            if (authCookie != null)
            {
                FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(authCookie.Value);

                if (ticket != null)
                {
                    string[] userData = { "" };

                    char[] delimiterChar = { '|' };
                    userData = ticket.UserData.Split(delimiterChar);
                    if (userData.Length > 1)
                        retValue = userData[ix];
                    else
                    {
                        FormsAuthentication.SignOut(); 

                        string redirUrl = "/DMC/loginNotFound.html";
                        HttpContext.Current.Response.Redirect(redirUrl, false);
                    }
                }
            }
        }

        return retValue;
    }

    private static string getUserName()
    {
        //This retrieves the person logged into windows/active directory
        WindowsPrincipal wp = new WindowsPrincipal(WindowsIdentity.GetCurrent());
        //string[] fullUsername = wp.Identity.Name.Split('\\');
        string fullUsername = wp.Identity.Name;

        return fullUsername;
    }

    private static string getFirstName()
    {
        string firstName = getUserDataString(1);

        return firstName;
    }

    private static string getPersonID()
    {
        string personID = getUserDataString(0);

        return personID;
    }

    private static string getSecBlur()
    {
        string secBlur = "no_secBlur";

        string mySQL = "exec get_UserAdminStatus @personID";
        string cf = System.Configuration.ConfigurationManager.ConnectionStrings["DistrictAssessmentDWConnectionString"].ConnectionString;

        SqlConnection connection = new SqlConnection(cf);
        SqlCommand command = new SqlCommand(mySQL, connection);

        command.Parameters.AddWithValue("@personID", getUserDataString(0));

        connection.Open();

        SqlDataReader dr = command.ExecuteReader();
        DataTable dt = new DataTable();
        dt.Load(dr);
        connection.Close();

        if (dt.Rows.Count > 0)
        {
            if (dt.Rows[0]["secBlur"].ToString() == "1")
                secBlur = "secBlur";

            fafsa = Convert.ToInt32(dt.Rows[0]["fafsa"]);
            staff = Convert.ToInt32(dt.Rows[0]["staff"]);
        }

        return secBlur;
    }
}

1 个答案:

答案 0 :(得分:-1)

如果给任何类静态的,则在进行任何访问之前,将调用所谓的“静态”(或类型)构造函数进行初始化工作:https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/static-constructors

进行初始化或定义默认值的另一种常用方法是使用“工厂模式”。 Xfa中的Afaik图形类必须根据在X-Box或PC上运行而进行调整,因此它使用出厂模式。

与Web(任何东西)无关的是,整个范围都存在变量Scope,即使对于静态变量也是如此。局部变量要少得多。

相关问题