Caching Web Method Response by Request ID

Julio Bello 221 Reputation points
2021-02-03T03:24:56.817+00:00

I developed a SOAP-based web service. I wish to log every request. I also wish to cache its response by its request ID, which is distinctly unique. Should the request be repeated within the hour, I want it to return the cached response.

My implementation does not work exactly. In fact, subsequent repeat requests circumvents my request log completely. Please see my "distilled" code below and kindly advise me exactly what I am doing wrong, please.

    [WebMethod(CacheDuration = 3600)]  // One hour duration
    public Response MyMethod(Request request)
    {
        try
        {
            if (LogRequestIsEnabled)
            {
                LogRequest(request);
            }

            if (Application[request.RequestID] != null)
            {
                return (Response)Application[request.requestID];
            }

            var response = new Response();

            //  Assign response properties...

            Application[request.RequestID] = response;

            return response;
        }
        catch (Exception ex)
        {
            var errorFormat =
                "{0}\n" +
                "parameter = {1}\n";
            var errorMessage = string.Format(errorFormat, ex, request);
            var newEx = new ApplicationException(FormatException(methodName, errorMessage), ex);

            return ErrorMessages(newEx);
        }
    }

When a repeat request is submitted, the cached response is returned, but the web method is not invoked at all, thus "short-circuiting" the request log feature.

ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,263 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,268 questions
ASP.NET API
ASP.NET API
ASP.NET: A set of technologies in the .NET Framework for building web applications and XML web services.API: A software intermediary that allows two applications to interact with each other.
297 questions
0 comments No comments
{count} votes

Accepted answer
  1. Julio Bello 221 Reputation points
    2021-02-03T06:26:53.21+00:00

    I found my answer...

    First...
    Replace [WebMethod(CacheDuration = 3600)] // One hour duration
    with [WebMethod]

    Second...
    Replace if (Application[request.RequestID] != null)
    with if (Context.Cache[request.RequestID] != null)

    Third...
    Replace return (Response)Application[request.requestID];
    with return (Response)Context.Cache[request.requestID];

    Finally...
    Replace Application[request.RequestID] = response;
    with Context.Cache.Insert(request.RequestID, response, null, DateTime.Now.AddHours(1), TimeSpan.Zero);

    0 comments No comments

0 additional answers

Sort by: Most helpful