Search code examples
c#asp.netweb-servicesasmx

In asp.net webservices (asmx), is the CacheDuration applied when called from code


When I set CacheDuration over a method in asmx service it gets applied correctly. Now if I called this method from another method in the same website or even from the same service, does this duration get applied too?


Solution

  • When you call the method which has cache duration:

    • Call from the same web site like a normal method → Calls without cache
    • Call from the same service like a normal method → Calls without cache
    • Call as a web service method (using service proxy) → Calls with cache

    The cache applies just when the call goes through ASP.NET pipeline. But if you call the method like a normal method, it doesn't use cache. In fact WebMethod attribute doesn't have any impact on calls when the call is a normal method call.

    Example

    I suppose you are looking for a simple test scenario, so you can create such web service to test:

    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    public class WebService1 : System.Web.Services.WebService
    {
        [WebMethod(CacheDuration=10)]
        public string GetDate1()
        {
            return DateTime.Now.ToString();
        }
    
        [WebMethod]
        public string GetDate2()
        {
            return this.GetDate1();
        }
    }
    

    1) To test calling method from the same project, in an aspx page you can write such code in a button click and run it 3-4 times to see the result:

    var svc = new WebService1();
    this.Label1.Text = string.Format("{0} | {1}", svc.GetDate1(), svc.GetDate2());
    

    In all executions you will see the time without any cache and you can see no difference between calling from the same site and calling from the same service.

    2) Also to test calling as web service method, add web reference to a windows forms project for example, in a button click write:

    var svc = new localhost.WebService1();
    MessageBox.Show(string.Format("{0} | {1}", svc.GetDate1(), svc.GetDate2()));
    

    Then you can see the svc.GetDate1() shows cached data and svc.GetDate2() shows current time while it uses svc.GetDate1() internally. So calling as a web service uses cache, but calling from the same web service doesn't use cache.