views:

54

answers:

3

I have a webservice (.asmx) and I want it to retain a value on a per-user basis. Is this possible?

ie (pseudo-code)

MyWebservice
{

object perUserVariable = something;

[WebMethod]
public void myMethod()
{
    if (something == null)
    {
      something = doBigExpensivedatabaseCall();
    }
    return something;
}

}
+2  A: 

You can use ASP.NET's session mechanism.
Change your WebMethod attribute, so that it will look like that:

[WebMethod(EnableSession = true)]  

This is normally achieved by cookies, or by sending the session id in the query string (both ways are completely handled by ASP.NET). The former is the default, to achieve the latter, just set cookieless="true" in your config.web file.

Oren A
A method cannot contain global variables so I'm not sure how that would work
SLC
@SLC - Why do you think a method can't use global variables?
Oren A
It can use them but it can't contain them... the perUserVariable in my post is not in the method, it's in the class - so I need to enable session on that surely
SLC
A: 

Yes, you would need to pass in some kind of user identifier to specify who the user is, do your operation and instead of storing it in something you will to use a durable or semi-durable store such as Cache or Session. Then look that value up from the Cache or Session instead of a local member.

Also fwiw the way you have that configured the fact something isn't static means it would be null on every single request because it would be newly initialized. Making it static however would then server the individual instance of something to each and every request there after.

This is why you need to use a store that can differentiate on the user such as Cache[userid+"something"] or the Session["something"] instead.

Chris Marisic
A: 

Your choices seem to be using some type of caching system like session or memcache.

Session will require a session id passed as a cookie to the requests. Other caching providers could probably key off of a post value like the userid.

Chris Lively