简体   繁体   中英

Add objects to list in web application

I've been trying to create a simple web application that registers users and saves their details using a list. Problem is that after adding the user successfully in the first call to the RegisterUser function, the list is empty again in the second call. Does it have anything to do with the fact that the function is an HTTP method?

code:

public class WS : System.Web.Services.WebService
{
    List<User> users = new List<User>();

    [WebMethod]
    [ScriptMethod(UseHttpGet = true)]
    public void registerUser()
    {
        try
        {
            string s = HttpContext.Current.Request.Form[0].ToString();
            User tempUser = new User();
            tempUser = JsonConvert.DeserializeObject<User>(s);
            users.Add(tempUser);
        }
        catch(Exception e)
        {
            HttpContext.Current.Response.Write(e.Message);
        }
    }
}
public class WS : System.Web.Services.WebService
{

    [WebMethod(EnableSession = true)]
    [ScriptMethod(UseHttpGet = true)]
    public void registerUser()
    {
        try
        {
            if(Session["users"] == null)
                Session["users"] = new List<User>();

            List<User> users = (List<User>)Session["users"];

            string s = HttpContext.Current.Request.Form[0].ToString();
            User tempUser = new User();
            tempUser = JsonConvert.DeserializeObject<User>(s);
            users.Add(tempUser);

            Session["users"] = users;
        }
        catch(Exception e)
        {
            HttpContext.Current.Response.Write(e.Message);
        }
    }
}

The users field will be instantiated every time a new instance of the WS class is created. To persist the data across calls you need to make it static . However, you will lose the data every time the web server service restarts so you should probably look at persisting to a database or other persistent data store instead.

Code:

private static List<User> users = new List<User>(); // could probably be readonly too

If this is intended to be a security solution and not just a data gathering exercise I would further suggest a rethink of what you are doing. .NET has a membership provider subsystem available which you should look into.

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