Exemplo n.º 1
0
        public async Task <HttpRequestSenderResponse> SendAsync(HttpRequestSenderInput input, CancellationToken cancellationToken)
        {
            HttpRequestSenderResponse result = null;

            using (var msg = BuildMessage(input))
            {
                using (var httpResponse = await _client.SendAsync(msg, HttpCompletionOption.ResponseHeadersRead, cancellationToken))
                {
                    result = BuildRequestResponse(httpResponse);

                    var isSucceed = httpResponse.IsSuccessStatusCode;

                    if (isSucceed && input.OnSuccess == null)
                    {
                        HttpRequestLog.Trace("Response succeed and no handler for success defined. so returning basic response");

                        return(result);
                    }

                    if (!isSucceed && input.OnFailure == null)
                    {
                        HttpRequestLog.Trace("Failed response and no handler for failure defined. so returning basic response");

                        return(result);
                    }

                    if (httpResponse.Content == null)
                    {
                        HttpRequestLog.Trace("Content empty so returning basic response");

                        return(result);
                    }

                    var rsp = new HttpResponseContent
                    {
                        ContentLength = httpResponse.Content.Headers.ContentLength ?? 0,
                        StatusCode    = httpResponse.StatusCode,
                        ContentType   = httpResponse.Content.Headers.ContentType?.MediaType,
                        Headers       = result.Headers
                    };

                    using (httpResponse.Content)
                    {
                        using (var sr = await httpResponse.Content.ReadAsStreamAsync())
                        {
                            rsp.ContentStream = sr;
                            rsp.StatusCode    = httpResponse.StatusCode;

                            if (isSucceed)
                            {
                                HttpRequestLog.Trace("Executing success handler");
                                await input.OnSuccess(rsp);
                            }
                            else
                            {
                                HttpRequestLog.Trace("Executing failure handler");
                                await input.OnFailure(rsp);
                            }
                        }
                    }
                }
            }

            return(result);
        }