I am calling a rest API as follows. I wonder if there are ways to improve/optimize the code. Should I add time-out or cancellation token? Any help would be appreciated.
public static async Task<HttpResponseMessage> CallTestRazer(GameRequest gameRequest, string url)
{
//FormUrlEncodedContent content = null;
HttpResponseMessage response = null;
//Transform GameRequest into ProductDTO
var config = new MapperConfiguration(cfg => { cfg.CreateMap<GameRequest, ProductRequestDto>(); });
var iMapper = config.CreateMapper();
var productRequest = iMapper.Map<GameRequest, ProductRequestDto>(gameRequest);
if (url == "Product/")
{
try
{
//HTTPWebRequest
var request = (HttpWebRequest) WebRequest.Create("http://test.com/store/" + url);
request.ContentType = "application/x-www-form-urlencoded";
request.Method = "POST";
var keyValueContent = productRequest.ToKeyValue();
var formUrlEncodedContent = new FormUrlEncodedContent(keyValueContent);
var urlEncodedString = await formUrlEncodedContent.ReadAsStringAsync();
using (var streamWriter = new StreamWriter(await request.GetRequestStreamAsync()))
{
streamWriter.Write(urlEncodedString);
}
HttpWebResponse httpResponse = (HttpWebResponse) (await request.GetResponseAsync());
response = new HttpResponseMessage
{
StatusCode = httpResponse.StatusCode,
Content = new StreamContent(httpResponse.GetResponseStream()),
};
return response;
}
catch (Exception ex)
{
Console.WriteLine(ex);
throw ;
}
}
else
{
try
{
//HTTPWebRequest
var request = (HttpWebRequest)WebRequest.Create("http://test.com/store/" + url);
request.ContentType = "application/x-www-form-urlencoded";
request.Method = "POST";
var keyValueContent = gameRequest.ToKeyValue();
var formUrlEncodedContent = new FormUrlEncodedContent(keyValueContent);
var urlEncodedString = await formUrlEncodedContent.ReadAsStringAsync();
using (var streamWriter = new StreamWriter(await request.GetRequestStreamAsync()))
{
streamWriter.Write(urlEncodedString);
}
HttpWebResponse httpResponse = (HttpWebResponse)(await request.GetResponseAsync());
string json;
using (Stream responseStream = httpResponse.GetResponseStream())
{
json = new StreamReader(responseStream).ReadToEnd();
}
response = new HttpResponseMessage
{
StatusCode = httpResponse.StatusCode,
Content = new StringContent(json, System.Text.Encoding.UTF8, "application/json"),
};
return response;
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
}
}
Here is the ToKeyValues:
public static IDictionary<string, string> ToKeyValues(this object metaToken)
{
if (metaToken == null)
{
return null;
}
JToken token = metaToken as JToken;
if (token == null)
{
return ToKeyValues(JObject.FromObject(metaToken));
}
if (token.HasValues)
{
var contentData = new Dictionary<string, string>();
foreach (var child in token.Children().ToList())
{
var childContent = child.ToKeyValues();
if (childContent != null)
{
contentData = contentData.Concat(childContent).ToDictionary(k => k.Key, v => v.Value);
}
}
return contentData;
}
var jValue = token as JValue;
if (jValue?.Value == null)
{
return null;
}
var value = jValue?.Type == JTokenType.Date
? jValue?.ToString("o", CultureInfo.InvariantCulture)
: jValue?.ToString(CultureInfo.InvariantCulture);
return new Dictionary<string, string> {{token.Path, value}};
}
HttpWebRequestyet still usingHttpResponseMessage? Why notHttpClient? \$\endgroup\$httpclientbut I got errors (System.Threading.Tasks.TaskCanceledException: A task was canceled) when I was load testing. One of the forums, somebody suggested me to useHttpWebRequest. After changing the code, the error didn't show up anymore. Long story short, I am sending HttpResponseMessage from service layer to controller. I am still using this logic in my code. \$\endgroup\$