0

I wrote this WebService in C#:

public class Service : IService
{
    TestClass testObject = new TestClass();

    public string GetData()
    {
        testObject.Counter++;
        return string.Format("Test Value: {0}", testObject.Counter);
    }
}

public class TestClass
{
    public int Counter { get; set; }

    public TestClass()
    {
        Counter = 0;
    }
}

It's a WebService and each time I invoke my WebService it recreates everthing. So my counter never increase and each time I invoke GetData() the WebService return "1".

What are the solutions to persist my data between each WebService invoke.

  1. Database, I would like to avoid this solution,
  2. State on the client, How ?
  3. session, Is there an easy way to use this?
  4. persistent service. Is this working?

Do you know articles than explain how to persist data with WebService?

Thank you,

Bastien Vandamme
  • 17,659
  • 30
  • 118
  • 200
  • If your webservice is only running on 1 server you can use session state or Cache. If your web services is running on more than one server then you will have to use a database to store the value. – Ken Tucker Jul 03 '14 at 10:23
  • What is the intended lifespan of the data you wish to persist? – CodeCaster Jul 03 '14 at 10:35

2 Answers2

1

It's called a stateful web service, by using Session for example. See here.

However, something to avoid in most cases, for scalability reasons. Your service calls should always be independent of each other.

Community
  • 1
  • 1
L-Four
  • 13,345
  • 9
  • 65
  • 109
  • Thanks for this interesting link. I have the same question as TraderJoeChicago: if you need state, what should you use. 1) Database, 2) State on the client, 3) session, 4) persistent service. Is there an easy way to use 3 ? Is 4 working ? In my case i would like to avoid the database for performance reasons. – Bastien Vandamme Jul 03 '14 at 10:30
  • What is your use case? – L-Four Jul 03 '14 at 11:19
0

You could track the counter in the HttpContext.Cache and increment the values there:

int counter = (int) HttpContext.Current.Cache["ServiceCallCounter"];
counter ++;
HttpContext.Current.Cache["ServiceCallCounter"] = counter;

Note that you have to activate it first and note that this cache does not persist a Application-Pool recycle:

<system.serviceModel>        
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" />
</system.serviceModel>
ovm
  • 2,452
  • 3
  • 28
  • 51