// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
namespace Microsoft.Graph
{
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
///
/// Provides method(s) to deserialize raw HTTP responses into strong types.
///
public class ResponseHandler : IResponseHandler
{
private readonly ISerializer serializer;
///
/// Constructs a new .
///
///
public ResponseHandler(ISerializer serializer)
{
this.serializer = serializer;
}
///
/// Process raw HTTP response into requested domain type.
///
/// The type to return
/// The HttpResponseMessage to handle
///
public async Task HandleResponse(HttpResponseMessage response)
{
if (response.Content != null)
{
var responseString = await GetResponseString(response);
return serializer.DeserializeObject(responseString);
}
return default(T);
}
///
/// Get the response content string
///
/// The response object
/// The full response string to return
private async Task GetResponseString(HttpResponseMessage hrm)
{
var responseContent = "";
var content = await hrm.Content.ReadAsStringAsync().ConfigureAwait(false);
//Only add headers if we are going to return a response body
if (content.Length > 0)
{
var responseHeaders = hrm.Headers;
var statusCode = hrm.StatusCode;
Dictionary headerDictionary = responseHeaders.ToDictionary(x => x.Key, x => x.Value.ToArray());
var responseHeaderString = serializer.SerializeObject(headerDictionary);
responseContent = content.Substring(0, content.Length - 1) + ", ";
responseContent += "\"responseHeaders\": " + responseHeaderString + ", ";
responseContent += "\"statusCode\": \"" + statusCode + "\"}";
}
return responseContent;
}
}
}