in RESTProxy/Models/Endpoint.cs [258:342]
public async Task<HttpResponseMessage> PerformRequestAsync(
string pathAndQuery,
HttpMethod method,
IPrincipal onBehalfOf,
string body = null,
string correlationId = null,
string clientRequestId = null,
string clientName = null)
{
// This is the real API endpoint that we'll be contacting. We'll just append
// pathAndQuery directly to this to get the final REST Uri that we need to use.
string finalUri = string.Format(
"{0}{1}",
this.BaseUri,
pathAndQuery);
WebRequest request = HttpWebRequest.Create(finalUri);
request.Method = method.ToString();
request.ContentLength = 0; // will be updated if there is a body.
try
{
HttpResponseMessage errorMessage;
// No reason to progress any further if they don't have the right permissions
// to access the API that they're trying to use.
if (!this.TryHasPermission(onBehalfOf, method, out errorMessage))
{
return errorMessage;
}
// Every API request needs to authenticate itself by providing an AccessToken
// in the authorization header.
string accessToken = await this.GetAccessTokenAsync();
request.Headers[HttpRequestHeader.Authorization] = string.Format("bearer {0}", accessToken);
if (!string.IsNullOrWhiteSpace(clientName))
{
request.Headers[ProxyManager.ClientNameHeader] = clientName;
}
// Add any additional headers that the client may have specified in their request
if (!string.IsNullOrWhiteSpace(correlationId))
{
request.Headers[ProxyManager.MSCorrelationIdHeader] = correlationId;
}
if (!string.IsNullOrWhiteSpace(clientRequestId))
{
request.Headers[ProxyManager.MSClientRequestIdHeader] = clientRequestId;
}
// Write the body to the request stream if one was provided.
// Not every REST API will require a body. For instance, the GET requests have
// no body, and the (current) POST API's also have no body.
if (!string.IsNullOrWhiteSpace(body))
{
byte[] bytes = System.Text.Encoding.UTF8.GetBytes(body);
request.ContentLength = bytes.Length;
request.ContentType = $"{ProxyManager.JsonMediaType}; charset=UTF-8";
using (Stream requestStream = await request.GetRequestStreamAsync())
{
requestStream.Write(bytes, 0, bytes.Length);
}
}
// Get the response.
using (WebResponse response = await request.GetResponseAsync())
{
// Even though we got a simple WebResponse, in our scenario we would prefer
// an HttpWebResponse since it exposes a StatusCode property.
HttpWebResponse httpResponse = response as HttpWebResponse;
return this.GetResponseMessage(httpResponse);
}
}
catch (WebException ex)
{
// Even though WebException stores the response as a simple WebResponse, in our scenario
// it should actually be an HttpWebResponse. We'd prefer that one, since HttpWebResponse
// exposes a StatusCode property.
HttpWebResponse httpResponse = ex.Response as HttpWebResponse;
return this.GetResponseMessage(httpResponse);
}
}