Question

I have a web service that queries data from this json file, but I don't want the web service to have to access the file every time. I'm thinking that maybe I can store the data somewhere else (maybe in memory) so the web service can just get the data from there the next time it's trying to query the same data. I kinda understand what needs to be done but I'm just not sure how to actually do it. How do we persist data in a web service?

Update: Both suggestions, caching and using static variables, look good. Maybe I should just use both so I can look at one first, and if it's not in there, use the second one, if it's not in there either, then I'll look at the json file.

Was it helpful?

Solution

Extending on Ice^^Heat's idea, you might want to think about where you would cache - either cache the contents of the json file in the Application cache like so:

Context.Cache.Insert("foo", _
                 Foo, _
                 Nothing, _
                 DateAdd(DateInterval.Minute, 30, Now()), _
                 System.Web.Caching.Cache.NoSlidingExpiration)

And then generate the results you need from that on every hit. Alternatively you can cache the webservice output on the function definition:

<WebMethod(CacheDuration:=60)> _
Public Function HelloWorld() As String
    Return "Hello World"
End Function

Info gathered from XML Web Service Caching Strategies.

OTHER TIPS

What about using a global or static collection object? Is that a good idea?

ASP.NET caching works just as well with Web services so you can implement regular caching as explained here: http://msdn.microsoft.com/en-us/library/aa478965.aspx

To echo klughing, if your JSON data isn't expected to change often, I think the simplest way to cache it is to use a static collection of some kind - perhaps a DataTable.

First, parse your JSON data into a System.Data.DataTable, and make it static in your Web service class. Then, access the static object. The data should stay cached until IIS recycles your application pool.

public class WebServiceClass
{
    private static DataTable _myData = null;
    public static DataTable MyData
    {
        get
        {
            if (_myData == null)
            {
                _myData = ParseJsonDataReturnDT();
            }
            return _myData;
        }
    }

    [WebMethod]
    public string GetData()
    {
        //... do some stuff with MyData and return a string ...
        return MyData.Rows[0]["MyColumn"].ToString();
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top