FireShock
FireShock

Reputation: 1122

Logging requests, responses and exceptions of WebClient

I want to log (save to db or file, etc.) all requests and responses with exceptions of WebClient. I use derived class: public class GzipWebClient : WebClient {...}

Where I should catch uploading requests with data, downloading responses and exceptions? Or should I override some methods?

Can I use "protected override WebRequest GetWebRequest(Uri address)" to catch data?

Some using:

    private T GetDeserializedResponse<T>(string url)
    {
        using (var wc = new GzipWebClient())
        {
            wc.Encoding = Encoding.UTF8;
            string fullUrl = BaseUrl + url;
            string response = wc.DownloadString(fullUrl);

            try
            {
                return JsonConvert.DeserializeObject<T>(response);
            }
            catch
            {
                _logger.Error(response);
                throw;
            }
        }
    }

or

        string url = shop.Warehouse != null ?
            string.Format("/api/v1/cabinet/{0}/shop_create.json", MasterApiKey) :
            string.Format("/api/v1/{0}/shop_create.json", MasterApiKey);

        string name = shop.Name;
        string namePostfix = DateTime.Now.ToString("yyMMddhhmmss");
        if ((name + namePostfix).Length > 64)
            name = name.Substring(0, 64 - namePostfix.Length);

        string data = shop.Warehouse != null ?
            string.Format("name={0}&warehouse={1}&address={2}", name + namePostfix, shop.Warehouse.Id, shop.Address) :
            string.Format("name={0}&address={1}", name + namePostfix, shop.Address);

        using (var wc = new GzipWebClient())
        {
            wc.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
            wc.Encoding = Encoding.UTF8;

            string fullUrl = BaseUrl + url;

            string response = wc.UploadString(fullUrl, data);

            var shopData = JsonConvert.DeserializeObject<DDeliveryCreateShopResponse>(response);

            if (!shopData.Success)
            {
                throw new DeliveryCreateStoreException(shop.Name);
            }

            if (string.IsNullOrEmpty(shopData.IdKeyPair.Key))
            {
                throw new DeliveryCreateStoreException(shop.Name);
            }

            shop.Id = shopData.IdKeyPair.Id;
            shop.Key = shopData.IdKeyPair.Key;
            return shop;
        }

Upvotes: 0

Views: 7143

Answers (2)

Niyoko
Niyoko

Reputation: 7672

For calling web service and if you use .Net 4.5, it's easier if you use HttpClient.

You can create LoggingHandler like this:

public class LoggingHandler : DelegatingHandler
{
    public LoggingHandler()
        : this(new HttpClientHandler())
    { }

    public LoggingHandler(HttpMessageHandler innerHandler)
        : base(innerHandler)
    { }

    protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        var activityId = Guid.NewGuid();
        using (new Tracer("Service Call", activityId))
        {
            var entry = new LogEntry { Severity = TraceEventType.Verbose, Title = "Request" };
            if (Logger.ShouldLog(entry))
            {
                entry.Message = request.ToString();
                if (request.Content != null)
                {
                    entry.Message += Environment.NewLine;
                    entry.Message += await request.Content
                        .ReadAsStringAsync()
                        .ConfigureAwait(false);
                }
                Logger.Write(entry);
            }

            var response = await base.SendAsync(request, cancellationToken).ConfigureAwait(false);

            entry = new LogEntry { Severity = TraceEventType.Verbose, Title = "Response" };
            if (Logger.ShouldLog(entry))
            {
                entry.Message = response.ToString();
                if (response.Content != null)
                    entry.Message += await response.Content
                        .ReadAsStringAsync()
                        .ConfigureAwait(false);

                Logger.Write(entry);
            }

            return response;
        }
    }
}

And then create HttpClient:

//hook all http request and response
var hc = new HttpClient(new LoggingHandler());

Documentation for HttpClient class: https://msdn.microsoft.com/en-us/library/system.net.http.httpclient%28v=vs.118%29.aspx

Comparing HttpClient and WebClient Need help deciding between HttpClient and WebClient

Upvotes: 3

clement
clement

Reputation: 4266

You have to log the Exceptiosn at the lowest point of your application , in your DAL if you have it in order to deal exceptions of your DB.

Upvotes: 0

Related Questions