Exemplo n.º 1
0
        /// <summary>
        /// Initialises a new instance of the <see cref="ApiException"/> class with the given components
        /// </summary>
        /// <param name="requestMethod"><see cref="HttpMethod"/> used to make the request which failed</param>
        /// <param name="requestUri"><see cref="Uri"/> to which the request which failed was made</param>
        /// <param name="statusCode"><see cref="HttpStatusCode"/> returned by the endpoint</param>
        /// <param name="reasonPhrase"><see cref="HttpResponseMessage.ReasonPhrase"/> provided by <see cref="HttpClient"/></param>
        /// <param name="headers"><see cref="HttpResponseHeaders"/>s associated with the response</param>
        /// <param name="contentHeaders"><see cref="HttpContentHeaders"/> associated with the response content, if there is a response content</param>
        /// <param name="contentString">String content, as read from <see cref="HttpContent.ReadAsStringAsync()"/>, if there is a response content</param>
        public ApiException(
            HttpMethod requestMethod,
            Uri?requestUri,
            HttpStatusCode statusCode,
            string?reasonPhrase,
            HttpResponseHeaders headers,
            HttpContentHeaders?contentHeaders,
            string?contentString)
            : base($"{requestMethod} \"{requestUri}\" failed because response status code does not indicate success: {(int)statusCode} ({reasonPhrase}).")
        {
            this.RequestMethod = requestMethod;
            this.Data[nameof(this.RequestMethod)] = requestMethod.Method;

            this.RequestUri = requestUri;
            this.Data[nameof(this.RequestUri)] = requestUri;

            this.StatusCode = statusCode;
            this.Data[nameof(this.StatusCode)] = statusCode;

            this.ReasonPhrase = reasonPhrase;
            this.Data[nameof(this.ReasonPhrase)] = reasonPhrase;

            this.Headers        = headers;
            this.ContentHeaders = contentHeaders;
            this.Content        = contentString;
        }
        /// <summary>
        ///     Determines the best <see cref="Encoding" /> amongst the supported encodings
        ///     for reading or writing an HTTP entity body based on the provided <paramref name="contentHeaders" />.
        /// </summary>
        /// <param name="contentHeaders">The content headers provided as part of the request or response.</param>
        /// <returns>The <see cref="Encoding" /> to use when reading the request or writing the response.</returns>
        public Encoding SelectCharacterEncoding(HttpContentHeaders?contentHeaders)
        {
            Encoding?encoding = null;

            if (contentHeaders != null && contentHeaders.ContentType != null)
            {
                // Find encoding based on content type charset parameter
                var charset = contentHeaders.ContentType.CharSet;
                if (!string.IsNullOrWhiteSpace(charset))
                {
                    encoding =
                        SupportedEncodings.FirstOrDefault(
                            enc => charset.Equals(enc.WebName, StringComparison.OrdinalIgnoreCase));
                }
            }

            // We didn't find a character encoding match based on the content headers.
            // Instead we try getting the default character encoding.
            encoding ??= SupportedEncodings.FirstOrDefault();

            if (encoding == null)
            {
                // No supported encoding was found so there is no way for us to start reading or writing.
                throw new InvalidOperationException(string.Format(Properties.Resources.MediaTypeFormatterNoEncoding,
                                                                  GetType().Name));
            }

            return(encoding);
        }
Exemplo n.º 3
0
 /// <summary>
 /// Initialises a new instance of the <see cref="ApiException"/> class with the given components
 /// </summary>
 /// <param name="requestMethod"><see cref="HttpMethod"/> used to make the request which failed</param>
 /// <param name="requestUri"><see cref="Uri"/> to which the request which failed was made</param>
 /// <param name="statusCode"><see cref="HttpStatusCode"/> returned by the endpoint</param>
 /// <param name="reasonPhrase"><see cref="HttpResponseMessage.ReasonPhrase"/> provided by <see cref="HttpClient"/></param>
 /// <param name="headers"><see cref="HttpResponseHeaders"/>s associated with the response</param>
 /// <param name="contentHeaders"><see cref="HttpContentHeaders"/> associated with the response content, if there is a response content</param>
 /// <param name="contentString">String content, as read from <see cref="HttpContent.ReadAsStringAsync()"/>, if there is a response content</param>
 public ApiException(
     HttpMethod requestMethod,
     Uri?requestUri,
     HttpStatusCode statusCode,
     string?reasonPhrase,
     HttpResponseHeaders headers,
     HttpContentHeaders?contentHeaders,
     string?contentString)
     : this(requestMethod, requestUri, statusCode, reasonPhrase, headers, contentHeaders, contentString, null)
 {
 }
Exemplo n.º 4
0
 public void AddStream(string name, Stream stream, Action?cleanup = null, HttpContentHeaders?headers = null)
 {
     Guard.AgainstNull(nameof(name), name);
     Guard.AgainstNull(nameof(stream), stream);
     Inner.Add(name,
               new Outgoing
               (
                   contentBuilder: cancellation => Task.FromResult <HttpContent>(new StreamContent(stream)),
                   cleanup: cleanup.WrapCleanupInCheck(name),
                   headers: headers
               ));
 }
Exemplo n.º 5
0
 public void AddBytes(string name, byte[] bytes, Action?cleanup = null, HttpContentHeaders?headers = null)
 {
     Guard.AgainstNull(nameof(name), name);
     Guard.AgainstNull(nameof(bytes), bytes);
     Inner.Add(name,
               new Outgoing
               (
                   contentBuilder: cancellation => Task.FromResult <HttpContent>(new ByteArrayContent(bytes)),
                   cleanup: cleanup.WrapCleanupInCheck(name),
                   headers: headers
               ));
 }
Exemplo n.º 6
0
        /// <summary>
        /// <see cref="ExtendedODataDeserializerProvider.GetODataDeserializer(System.Type, HttpRequestMessage)"/>
        /// <see cref="DefaultODataActionCreateUpdateParameterDeserializer.Read(Microsoft.OData.ODataMessageReader, System.Type, Microsoft.AspNet.OData.Formatter.Deserialization.ODataDeserializerContext)"/>
        /// </summary>
        public override async Task OnAuthorizationAsync(HttpActionContext actionContext, CancellationToken cancellationToken)
        {
            if (actionContext == null)
            {
                throw new ArgumentNullException(nameof(actionContext));
            }

            HttpActionDescriptor actionDescriptor = actionContext.Request.GetActionDescriptor();

            HttpContentHeaders?requestContentHeaders = actionContext.Request?.Content?.Headers;

            if (requestContentHeaders != null)
            {
                bool contentLengthHasValue = requestContentHeaders.ContentLength != null;
                bool contentTypeIsJson     = requestContentHeaders.ContentType?.MediaType?.Contains("json", StringComparison.InvariantCultureIgnoreCase) == true; // https://github.com/aspnet/AspNetWebStack/issues/232

                if (((contentLengthHasValue && requestContentHeaders.ContentLength > 0) || (!contentLengthHasValue && contentTypeIsJson)) && (actionDescriptor.GetCustomAttributes <ActionAttribute>().Any() ||
                                                                                                                                              actionDescriptor.GetCustomAttributes <CreateAttribute>().Any() ||
                                                                                                                                              actionDescriptor.GetCustomAttributes <UpdateAttribute>().Any() ||
                                                                                                                                              actionDescriptor.GetCustomAttributes <PartialUpdateAttribute>().Any()))
                {
                    using (Stream responseContent = await actionContext.Request !.Content !.ReadAsStreamAsync().ConfigureAwait(false))
                        using (StreamReader requestStreamReader = new StreamReader(responseContent))
                        {
                            using (JsonReader jsonReader = new JsonTextReader(requestStreamReader))
                            {
                                JToken contentStreamAsJson = await JToken.LoadAsync(jsonReader, cancellationToken).ConfigureAwait(false) !;

                                if (contentStreamAsJson.First is JProperty prop && actionDescriptor.GetParameters().Any(p => p.ParameterName == prop.Name))
                                {
                                    contentStreamAsJson = contentStreamAsJson[prop.Name] !;
                                }

                                actionContext.Request.Properties["ContentStreamAsJson"] = contentStreamAsJson;
                            }
                        }
                }
            }

            await base.OnAuthorizationAsync(actionContext, cancellationToken).ConfigureAwait(false);
        }
Exemplo n.º 7
0
 public void AddBytes(string name, Func <byte[]> bytesFactory, Action?cleanup = null, HttpContentHeaders?headers = null)
 {
     Guard.AgainstNull(nameof(name), name);
     Guard.AgainstNull(nameof(bytesFactory), bytesFactory);
     Inner.Add(name,
               new Outgoing
               (
                   contentBuilder: cancellation =>
     {
         bytesFactory = bytesFactory.WrapFuncInCheck(name);
         var value    = bytesFactory();
         return(Task.FromResult <HttpContent>(new ByteArrayContent(value)));
     },
                   cleanup: cleanup.WrapCleanupInCheck(name),
                   headers: headers
               ));
 }
Exemplo n.º 8
0
 public void AddBytes(byte[] bytes, Action?cleanup = null, HttpContentHeaders?headers = null)
 {
     AddBytes("default", bytes, cleanup, headers);
 }
Exemplo n.º 9
0
 public void AddBytes(Func <byte[]> bytesFactory, Action?cleanup = null, HttpContentHeaders?headers = null)
 {
     AddBytes("default", bytesFactory, cleanup, headers);
 }
Exemplo n.º 10
0
 public void AddStream(Func <Stream> streamFactory, Action?cleanup = null, HttpContentHeaders?headers = null)
 {
     AddStream("default", streamFactory, cleanup, headers);
 }
Exemplo n.º 11
0
 public void AddStream <T>(string name, Func <CancellationToken, Task <T> > streamFactory, Action?cleanup = null, HttpContentHeaders?headers = null)
     where T : Stream
 {
     Guard.AgainstNull(nameof(name), name);
     Guard.AgainstNull(nameof(streamFactory), streamFactory);
     Inner.Add(name,
               new Outgoing
               (
                   contentBuilder: async cancellation =>
     {
         streamFactory = streamFactory.WrapFuncTaskInCheck(name);
         var value     = await streamFactory(cancellation);
         return(new StreamContent(value));
     },
                   cleanup: cleanup.WrapCleanupInCheck(name),
                   headers: headers
               ));
 }
Exemplo n.º 12
0
 public void AddString(Func <CancellationToken, Task <string> > valueFactory, Action?cleanup = null, HttpContentHeaders?headers = null)
 {
     AddString("default", valueFactory, cleanup, headers);
 }
Exemplo n.º 13
0
 public void AddStream <T>(Func <CancellationToken, Task <T> > streamFactory, Action?cleanup = null, HttpContentHeaders?headers = null)
     where T : Stream
 {
     AddStream("default", streamFactory, cleanup, headers);
 }
Exemplo n.º 14
0
 public void AddString(string value, Action?cleanup = null, HttpContentHeaders?headers = null)
 {
     AddString("default", value, cleanup, headers);
 }
Exemplo n.º 15
0
 public void AddBytes(string name, Func <CancellationToken, Task <byte[]> > bytesFactory, Action?cleanup = null, HttpContentHeaders?headers = null)
 {
     Guard.AgainstNull(nameof(name), name);
     Guard.AgainstNull(nameof(bytesFactory), bytesFactory);
     Inner.Add(name,
               new Outgoing
               (
                   contentBuilder: async cancellation =>
     {
         bytesFactory = bytesFactory.WrapFuncTaskInCheck(name);
         var value    = await bytesFactory(cancellation);
         return(new ByteArrayContent(value));
     },
                   cleanup: cleanup.WrapCleanupInCheck(name),
                   headers: headers
               ));
 }
Exemplo n.º 16
0
 public Outgoing(Func <CancellationToken, Task <HttpContent> > contentBuilder, Action?cleanup, HttpContentHeaders?headers)
 {
     ContentBuilder = contentBuilder;
     Cleanup        = cleanup;
     Headers        = headers;
 }
Exemplo n.º 17
0
 public void AddStream(Stream stream, Action?cleanup = null, HttpContentHeaders?headers = null)
 {
     AddStream("default", stream, cleanup, headers);
 }
Exemplo n.º 18
0
 public void AddStream(string name, Func <Stream> streamFactory, Action?cleanup = null, HttpContentHeaders?headers = null)
 {
     Guard.AgainstNull(nameof(name), name);
     Guard.AgainstNull(nameof(streamFactory), streamFactory);
     Inner.Add(name,
               new Outgoing
               (
                   contentBuilder: cancellation =>
     {
         streamFactory = streamFactory.WrapFuncInCheck(name);
         var value     = streamFactory();
         return(Task.FromResult <HttpContent>(new StreamContent(value)));
     },
                   cleanup: cleanup.WrapCleanupInCheck(name),
                   headers: headers
               ));
 }
 public static IHttpContentHeaders?ToInterface(this HttpContentHeaders?headers)
 {
     return((headers == null) ? null : new HttpContentHeadersAdapter(headers));
 }