예제 #1
0
        public async Task <HttpResponseMessage> GetHttpResponseMessageFromRequest <TResponse>
        (
            IApiRequest aApiRequest
        )
        {
            HttpVerb      httpverb    = aApiRequest.GetHttpVerb();
            StringContent httpContent = null;

            if (httpverb == HttpVerb.Post || httpverb == HttpVerb.Put || httpverb == HttpVerb.Patch)
            {
                string requestAsJson = JsonSerializer.Serialize(aApiRequest, aApiRequest.GetType());

                httpContent =
                    new StringContent
                    (
                        requestAsJson,
                        Encoding.UTF8,
                        MediaTypeNames.Application.Json
                    );
            }

            return(httpverb switch
            {
                HttpVerb.Get => await HttpClient.GetAsync(aApiRequest.GetRoute()).ConfigureAwait(false),
                HttpVerb.Delete => await HttpClient.DeleteAsync(aApiRequest.GetRoute()).ConfigureAwait(false),
                HttpVerb.Post => await HttpClient.PostAsync(aApiRequest.GetRoute(), httpContent).ConfigureAwait(false),
                HttpVerb.Put => await HttpClient.PutAsync(aApiRequest.GetRoute(), httpContent).ConfigureAwait(false),
                HttpVerb.Patch => await HttpClient.PatchAsync(aApiRequest.GetRoute(), httpContent).ConfigureAwait(false),
                _ => null,
            });
예제 #2
0
        public TResponse Execute <TResponse>(IApiRequest <TResponse> request, HttpContext context = null)
            where TResponse : class, IApiResponse, new()
        {
            if (this != Instance)
            {
                return(Instance.Execute(request, context));
            }
            IApiHandler handler = null;

            try
            {
                var type = typeof(ApiHandler <,>).MakeGenericType(request.GetType(), typeof(TResponse));
                handler = this.Resolve <IApiHandler>(type) ?? throw new Exception();
            }
            catch (Exception e)
            {
                throw new ResolveException("Resolve Error: " + e.Message);
            }
            if (handler == null)
            {
                throw new ResolveException("Handler Resolve Failed");
            }
            if (context != null)
            {
                handler.HttpContext = context;
            }
            try
            {
                return(handler.Execute(request) as TResponse);
            }
            catch (Exception e)
            {
                throw e;
            }
        }
예제 #3
0
        public void FireRequestFailureEvent(IApiRequest request, IApiResponse response, RequestFailureReason reason, Action onResume = null, bool foregroundAction = false)
        {
            LogUtility.LogMessage(String.Format("firing RequestFailure event (request type:{0}, reason:{1}, callback:{2}, foreground:{3})",
                                                (request != null ? request.GetType().Name : "<null>"),
                                                Enum.GetName(typeof(RequestFailureReason), reason),
                                                (onResume == null ? "no" : "yes"),
                                                (foregroundAction ? "yes" : "no")));

            if (this._requestFailed != null)
            {
                this._requestFailed(this, new RequestFailureEventArgs(request, response, reason, foregroundAction, onResume));
            }
        }
        public async Task <IApiResponse <T> > ExecuteAsync <T>(IApiRequest request)
            where T : class
        {
            // Need to account for special cases when the return type is a stream
            bool isStream = typeof(T) == typeof(Stream);

            HttpRequestMessage httpRequest = request.GetType() == typeof(ApiMultiPartRequest) ?
                                             BuildMultiPartRequest(request as ApiMultiPartRequest) :
                                             BuildRequest(request);

            // Add headers
            foreach (var kvp in request.HttpHeaders)
            {
                httpRequest.Headers.TryAddWithoutValidation(kvp.Key, kvp.Value);
            }

            // If we are retrieving a stream, we should return without reading the entire response
            HttpCompletionOption completionOption = isStream ?
                                                    HttpCompletionOption.ResponseHeadersRead :
                                                    HttpCompletionOption.ResponseContentRead;

            Debug.WriteLine(string.Format("RequestUri: {0}", httpRequest.RequestUri));//, RequestHeader: {1} , httpRequest.Headers.Select(i => string.Format("{0}:{1}", i.Key, i.Value)).Aggregate((i, j) => i + "," + j)));

            try
            {
                HttpClient          client   = CreateClient(request);
                HttpResponseMessage response = await client.SendAsync(httpRequest, completionOption).ConfigureAwait(false);

                ApiResponse <T> apiResponse = new ApiResponse <T>();
                apiResponse.Headers = response.Headers;

                // Translate the status codes that interest us
                apiResponse.StatusCode = response.StatusCode;
                switch (response.StatusCode)
                {
                case HttpStatusCode.OK:
                case HttpStatusCode.Created:
                case HttpStatusCode.NoContent:
                    apiResponse.Status = ResponseStatus.Success;
                    break;

                case HttpStatusCode.Accepted:
                    apiResponse.Status = ResponseStatus.Pending;
                    break;

                case HttpStatusCode.Unauthorized:
                    apiResponse.Status = ResponseStatus.Unauthorized;
                    break;

                default:
                    apiResponse.Status = ResponseStatus.Error;
                    break;
                }

                if (isStream && apiResponse.Status == ResponseStatus.Success)
                {
                    var resObj = await response.Content.ReadAsStreamAsync().ConfigureAwait(false);

                    apiResponse.ResponseObject = resObj as T;
                }
                else
                {
                    apiResponse.ContentString = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
                }
                return(apiResponse);
            }
            catch (Exception ex)
            {
                Debug.WriteLine(string.Format("Exception: {0}", ex.Message));
                throw;
            }
        }
예제 #5
0
 public void FireRequestSucceededEvent(IApiRequest request, IApiResponse response)
 {
     LogUtility.LogMessage(String.Format("firing RequestSucceededEvent event (request type: {0})", (request != null ? request.GetType().Name : "<null>")));
     if (this._requestSucceeded != null)
     {
         this._requestSucceeded(this, new RequestEventArgs(request, response));
     }
 }