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;
}