Akamai.EdgeGrid.Auth.EdgeGridV1Signer.Validate C# (CSharp) Method

Validate() public method

Validates the response and attempts to detect root causes for failures for non 200 responses. The most common cause is due to time synchronization of the local server. If the local server is more than 30seconds out of sync then the API server will reject the request. TODO: catch rate limitting errors. Should delay and retry.
public Validate ( WebResponse response ) : void
response System.Net.WebResponse the active response object
return void
        public void Validate(WebResponse response)
        {
            if (response is HttpWebResponse)
            {
                HttpWebResponse httpResponse = (HttpWebResponse)response;
                if (httpResponse.StatusCode == HttpStatusCode.OK)
                    return;

                DateTime responseDate;
                string date = response.Headers.Get("Date");
                if (date != null
                    && DateTime.TryParse(date, out responseDate))
                    if (DateTime.Now.Subtract(responseDate).TotalSeconds > 30)
                        throw new HttpRequestException("Local server Date is more than 30s out of sync with Remote server");

                string responseBody = null;
                using (var reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
                {
                    responseBody = reader.ReadToEnd();
                    // Do something with the value
                }

                throw new HttpRequestException(string.Format("Unexpected Response from Server: {0} {1}\n{2}\n\n{3}", httpResponse.StatusCode, httpResponse.StatusDescription, response.Headers, responseBody));
            }
        }

Usage Example

        public void TestAPIActionValidateDateDrift()
        {
            string TestURIProtocol = "asdf";

            WebRequest.RegisterPrefix(TestURIProtocol, new WebRequestTestCreate());
            var request = (HttpWebRequestTest)WebRequest.Create("asdf://www.example.com/");


            var signer   = new EdgeGridV1Signer();
            var response = request.CreateResponse(HttpStatusCode.ServiceUnavailable, "Server Unavailable");

            var currentDate = DateTime.UtcNow.AddMinutes(-2);
            var headers     = new WebHeaderCollection {
                { "Date", currentDate.ToString("r") }
            };

            response = request.CreateResponse(HttpStatusCode.ServiceUnavailable, "Server Unavailable", headers);
            try
            {
                signer.Validate(response);
            }
            catch (Exception ex)
            {
                Assert.AreEqual(ex.Message, "Local server Date is more than 30s out of sync with Remote server");
                throw ex;
            }
        }
All Usage Examples Of Akamai.EdgeGrid.Auth.EdgeGridV1Signer::Validate