예제 #1
0
        private bool ValidateAcceptsSData(HttpHeaderValueCollection <MediaTypeWithQualityHeaderValue> acceptHeader)
        {
            if (acceptHeader != null && !acceptHeader.Any(x => x.MediaType == ALL_MEDIA_TYPE))
            {
                bool acceptsJson = acceptHeader.Any(x => x.MediaType == JSON_MEDIA_TYPE);

                if (!acceptsJson)
                {
                    return(false);
                }

                bool acceptsSData = acceptHeader.Any(x => x.MediaType == JSON_MEDIA_TYPE &&
                                                     x.Parameters.Any(p => p.Name == SDATA_MEDIA_TYPE_VALUE_VND));

                if (!acceptsSData)
                {
                    // does not mention SData check if OData mentioned
                    bool acceptsOData = acceptHeader.Any(x => x.MediaType == JSON_MEDIA_TYPE &&
                                                         x.Parameters.Any(p => p.Name == ODATA_MEDIA_TYPE_VALUE_VND));

                    if (acceptsOData)
                    {
                        // OData JSON Request; i.e. Accept header equals: application/json;odata=[verbose, etc]
                        return(false);
                    }

                    // consumer asked for JSON but did not indicated SData or OData so default is return SData; just continue
                }
            }

            return(true);
        }
        public Func <Stream, Stream> GetEncoder(
            HttpHeaderValueCollection <StringWithQualityHeaderValue> list)
        {
            if (list != null && list.Count > 0)
            {
                var headerValue = list.OrderByDescending(e => e.Quality ?? 1.0D)
                                  .Where(e => !e.Quality.HasValue ||
                                         e.Quality.Value > 0.0D)
                                  .FirstOrDefault(e => supported.Keys
                                                  .Contains(e.Value, StringComparer.OrdinalIgnoreCase));

                // Case 1: We can support what client has asked for
                if (headerValue != null)
                {
                    return(GetStreamForSchema(headerValue.Value));
                }


                // Case 2: Client is okay to accept any thing we support except
                // the ones explicitly specified as not preferred by setting q=0
                if (list.Any(e => e.Value == "*" &&
                             (!e.Quality.HasValue || e.Quality.Value > 0.0D)))
                {
                    var encoding = supported.Keys.Where(se =>
                                                        !list.Any(e =>
                                                                  e.Value.Equals(se, StringComparison.OrdinalIgnoreCase) &&
                                                                  e.Quality.HasValue &&
                                                                  e.Quality.Value == 0.0D))
                                   .FirstOrDefault();
                    if (encoding != null)
                    {
                        return(GetStreamForSchema(encoding));
                    }
                }

                // Case 3: Client specifically refusing identity
                if (list.Any(e => e.Value.Equals(IDENTITY, StringComparison.OrdinalIgnoreCase) &&
                             e.Quality.HasValue && e.Quality.Value == 0.0D))
                {
                    throw new NegotiationFailedException();
                }

                // Case 4: Client is not willing to accept one of the encodings
                // we support and is not willing to accept identity
                if (list.Any(e => e.Value == "*" &&
                             (e.Quality.HasValue || e.Quality.Value == 0.0D)))
                {
                    if (!list.Any(e => e.Value.Equals(IDENTITY, StringComparison.OrdinalIgnoreCase)))
                    {
                        throw new NegotiationFailedException();
                    }
                }
            }

            // Settle for the default, which is no transformation whatsoever
            return(null);
        }
예제 #3
0
        public bool RequestingAttachment()
        {
            HttpHeaderValueCollection <MediaTypeWithQualityHeaderValue> incomingMediaTypes = requestMessage.Headers.Accept;

            if (!incomingMediaTypes.Any() || incomingMediaTypes.Any(mt => RestUtils.IsJsonMediaType(mt.MediaType)))
            {
                return(false);
            }

            return(true);
        }
예제 #4
0
        public void ValidateIncomingMediaTypeAsJson()
        {
            if (AcceptHeaderStrict)
            {
                HttpHeaderValueCollection <MediaTypeWithQualityHeaderValue> incomingMediaTypes = requestMessage.Headers.Accept;

                if (!incomingMediaTypes.Any() || incomingMediaTypes.Any(mt => RestUtils.IsJsonMediaType(mt.MediaType)))
                {
                    return;
                }

                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.NotAcceptable));
            }
        }
예제 #5
0
        public Func <Stream, Stream> GetEncoder(HttpHeaderValueCollection <StringWithQualityHeaderValue> list)
        {
            if (list != null && list.Count() > 0)
            {
                var headerValue = list.OrderByDescending(e => e.Quality ?? 1.0D)
                                  .Where(e => !e.Quality.HasValue ||
                                         e.Quality.Value > 0.0D)
                                  .FirstOrDefault(e => supported.Keys
                                                  .Contains(e.Value, StringComparer.OrdinalIgnoreCase));

                if (headerValue != null)
                {
                    return(GetStreamForSchema(headerValue.Value));
                }

                if (list.Any(e => e.Value == "*" &&
                             (!e.Quality.HasValue || e.Quality.Value > 0.0D)))
                {
                    var encoding = supported.Keys.Where(se =>
                                                        !list.Any(e =>
                                                                  e.Value.Equals(se, StringComparison.OrdinalIgnoreCase) &&
                                                                  e.Quality.HasValue &&
                                                                  e.Quality.Value == 0.0D))
                                   .FirstOrDefault();
                    if (encoding != null)
                    {
                        return(GetStreamForSchema(encoding));
                    }
                }

                if (list.Any(e => e.Value.Equals(IDENTITY, StringComparison.OrdinalIgnoreCase) &&
                             e.Quality.HasValue && e.Quality.Value == 0.0D))
                {
                    throw new NegotiationFailedException();
                }

                // Case 4: Client is not willing to accept one of the encodings
                // we support and is not willing to accept identity
                if (list.Any(e => e.Value == "*" &&
                             (e.Quality.HasValue || e.Quality.Value == 0.0D)))
                {
                    if (!list.Any(e => e.Value.Equals(IDENTITY, StringComparison.OrdinalIgnoreCase)))
                    {
                        throw new NegotiationFailedException();
                    }
                }
            }
            return(null);
        }
 private static bool IsRequestedMediaTypeAccepted(HttpHeaderValueCollection<MediaTypeWithQualityHeaderValue> acceptHeader)
 {
     return GlobalConfiguration
         .Configuration
         .Formatters
         .Any(formatter => acceptHeader.Any(mediaType => FormatterSuportsMediaType(mediaType, formatter)));
 }
예제 #7
0
        internal static Task <HttpResponseMessage> CreateODataBatchResponseAsync(this HttpRequestMessage request, IEnumerable <ODataBatchResponseItem> responses, ODataMessageQuotas messageQuotas)
        {
            Contract.Assert(request != null);

            ODataVersion               odataVersion     = ResultHelpers.GetODataResponseVersion(request);
            IServiceProvider           requestContainer = request.GetRequestContainer();
            ODataMessageWriterSettings writerSettings   =
                requestContainer.GetRequiredService <ODataMessageWriterSettings>();

            writerSettings.Version       = odataVersion;
            writerSettings.MessageQuotas = messageQuotas;
            HttpHeaderValueCollection <MediaTypeWithQualityHeaderValue> acceptHeaderValues = request.Headers.Accept;

            MediaTypeHeaderValue responseContentType = null;

            if (!acceptHeaderValues.Any())
            {
                // In absence of accept, if request was JSON then default response to be JSON.
                // Note that, if responseContentType is not set, then it will default to multipart/mixed
                // when constructing the BatchContent, so we don't need to handle that case here
                if (request.Content != null && request.Content.Headers.Any(h => String.Equals(h.Key, ODataBatchHttpRequestMessageExtensions.ContentType, StringComparison.OrdinalIgnoreCase) &&
                                                                           h.Value.Any(v => v.IndexOf(ODataBatchHttpRequestMessageExtensions.BatchMediaTypeJson, StringComparison.OrdinalIgnoreCase) > -1)))
                {
                    responseContentType = MediaTypeHeaderValue.Parse(ODataBatchHttpRequestMessageExtensions.BatchMediaTypeJson);
                }
            }
            else if (acceptHeaderValues.Any(
                         t => t.MediaType.Equals(ODataBatchHttpRequestMessageExtensions.BatchMediaTypeMime, StringComparison.OrdinalIgnoreCase)))
            {
                responseContentType = MediaTypeHeaderValue.Parse(
                    String.Format(CultureInfo.InvariantCulture, "multipart/mixed;boundary=batchresponse_{0}",
                                  Guid.NewGuid()));
            }
            else if (acceptHeaderValues.Any(
                         t => t.MediaType.Equals(ODataBatchHttpRequestMessageExtensions.BatchMediaTypeJson, StringComparison.OrdinalIgnoreCase)))
            {
                responseContentType = MediaTypeHeaderValue.Parse(ODataBatchHttpRequestMessageExtensions.BatchMediaTypeJson);
            }

            HttpResponseMessage response = request.CreateResponse(HttpStatusCode.OK);

            response.Content = new ODataBatchContent(responses, requestContainer, responseContentType);
            return(Task.FromResult(response));
        }
예제 #8
0
        public Func<Stream, Stream> GetEncoder(HttpHeaderValueCollection<StringWithQualityHeaderValue> list)
        {
            // The following steps will walk you through
            // completing the implementation of this method
            if (list != null && list.Count > 0)
            {
                // More code goes here
                var headerValue = list.OrderByDescending(e => e.Quality ?? 1.0D).Where(e => !e.Quality.HasValue || e.Quality.Value > 0.0D).FirstOrDefault(e => supported.Keys.Contains(e.Value, StringComparer.OrdinalIgnoreCase));
                // Case 1: We can support what client has asked for
                if (headerValue != null)
                    return GetStreamForSchema(headerValue.Value);
                // Case 2: Client will accept anything we support except
                // the ones explicitly specified as not preferred by setting q=0
                if (list.Any(e => e.Value == "*" &&
                (!e.Quality.HasValue || e.Quality.Value > 0.0D)))
                {
                    var encoding = supported.Keys.Where(se =>
                    !list.Any(e =>
                    e.Value.Equals(se, StringComparison.OrdinalIgnoreCase) &&
                    e.Quality.HasValue &&
                    e.Quality.Value == 0.0D))
                    .FirstOrDefault();
                    if (encoding != null)
                        return GetStreamForSchema(encoding);
                }

                // Case 3: Client specifically refusing identity
                if (list.Any(e => e.Value.Equals(IDENTITY, StringComparison.OrdinalIgnoreCase) &&
                e.Quality.HasValue && e.Quality.Value == 0.0D))
                {
                    throw new NegotiationFailedException();
                }
                // Case 4: Client is not willing to accept any of the encodings
                // we support and is not willing to accept identity
                if (list.Any(e => e.Value == "*" &&
                (e.Quality.HasValue || e.Quality.Value == 0.0D)))
                {
                    if (!list.Any(e => e.Value.Equals(IDENTITY, StringComparison.OrdinalIgnoreCase)))
                        throw new NegotiationFailedException();
                }
            }
            // Settle for the default, which is no transformation whatsoever
            return null;
        }
        internal static HttpHeaderValueCollection <T> AddDistinct <T>(this HttpHeaderValueCollection <T> headers, Func <T, bool> predicate, string value)
            where T : class
        {
            if (!headers.Any(predicate))
            {
                headers.ParseAdd(value);
            }

            return(headers);
        }
        /// <summary>
        /// Validates if the current request is from admin tool
        /// </summary>
        /// <param name="actionContext">context for the http request containing the user agent string.</param>
        /// <returns>Boolean value indicating is request from admin tool or not.</returns>
        private bool IsRequestFromAdminUserAgent(HttpActionContext actionContext)
        {
            if (string.IsNullOrWhiteSpace(UnityMvcActivator.AdminToolProductToken))
            {
                return(false);
            }

            HttpHeaderValueCollection <ProductInfoHeaderValue> userAgents = actionContext.Request.Headers.UserAgent;

            // Note: Check if, product token obtained from the current request matches with configured internal admin/developer tool product token.
            return(userAgents != null && userAgents.Any(productInfoHeader => string.Compare(productInfoHeader.Product.Name, UnityMvcActivator.AdminToolProductToken, StringComparison.OrdinalIgnoreCase) == 0));
        }
        protected override async Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            HttpHeaderValueCollection <StringWithQualityHeaderValue> acceptedLanguages = request.Headers.AcceptLanguage;

            if (acceptedLanguages.IsNotNullOrEmpty())
            {
                StringWithQualityHeaderValue headerValue = acceptedLanguages.OrderByDescending(e => e.Quality ?? 1.0D)
                                                           .Where(e => !e.Quality.HasValue || e.Quality.Value > 0.0D)
                                                           .FirstOrDefault(e => supportedCultures.Contains(e.Value, StringComparer.OrdinalIgnoreCase));

                string culture = null;
                // Case 1: We can support what client has asked for
                if (headerValue.IsNotNull())
                {
                    culture = headerValue.Value;
                }
                // Case 2: Client is okay to accept any thing we support except
                // the ones explicitly specified as not preferred by setting q=0
                else if (acceptedLanguages.Any(e => e.Value == "*" && (!e.Quality.HasValue || e.Quality.Value > 0.0D)))
                {
                    culture = supportedCultures.Where(sc =>
                                                      !acceptedLanguages.Any(e =>
                                                                             e.Value.Equals(sc, StringComparison.OrdinalIgnoreCase) &&
                                                                             e.Quality.HasValue &&
                                                                             e.Quality.Value == 0.0D))
                              .FirstOrDefault();
                }

                if (culture.IsNotNull())
                {
                    Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo(culture);
                    Thread.CurrentThread.CurrentCulture   = Thread.CurrentThread.CurrentUICulture;
                }
            }
            return(await base.SendAsync(request, cancellationToken));
        }
        public override void OnActionExecuting(HttpActionContext context)
        {
            HttpRequestMessage request = context.Request;

            if (request.Method == HttpMethod.Get)
            {
                string key = GetKey(request);
                HttpHeaderValueCollection <EntityTagHeaderValue> etagsFromClient = request.Headers.IfNoneMatch;
                if (etagsFromClient.Count > 0)
                {
                    EntityTagHeaderValue etag = null;
                    if (etags.TryGetValue(key, out etag) && etagsFromClient.Any(t => t.Tag == etag.Tag))
                    {
                        context.Response = new HttpResponseMessage(HttpStatusCode.NotModified);
                    }
                }
            }
        }
 private static bool IsRequestedMediaTypeAccepted(HttpHeaderValueCollection <MediaTypeWithQualityHeaderValue> acceptHeader)
 {
     return(Enumerable.Any <MediaTypeFormatter>(GlobalConfiguration
                                                .Configuration
                                                .Formatters, formatter => acceptHeader.Any(mediaType => FormatterSuportsMediaType(mediaType, formatter))));
 }
 private bool IsRequestedMediaTypeAccepted(HttpHeaderValueCollection <MediaTypeWithQualityHeaderValue> acceptHeader)
 {
     return(configuration
            .Formatters
            .Any(formatter => acceptHeader.Any(mediaType => FormatterSuportsMediaType(mediaType, formatter))));
 }
예제 #15
0
        private bool ValidateAcceptsSData(HttpHeaderValueCollection<MediaTypeWithQualityHeaderValue> acceptHeader)
        {
            if (acceptHeader != null && !acceptHeader.Any(x => x.MediaType == ALL_MEDIA_TYPE))
            {
                bool acceptsJson = acceptHeader.Any(x => x.MediaType == JSON_MEDIA_TYPE);

                if (!acceptsJson)
                {
                    return false;
                }

                bool acceptsSData = acceptHeader.Any(x => x.MediaType == JSON_MEDIA_TYPE &&
                                    x.Parameters.Any(p => p.Name == SDATA_MEDIA_TYPE_VALUE_VND));

                if (!acceptsSData)
                {
                    // does not mention SData check if OData mentioned
                    bool acceptsOData = acceptHeader.Any(x => x.MediaType == JSON_MEDIA_TYPE &&
                                        x.Parameters.Any(p => p.Name == ODATA_MEDIA_TYPE_VALUE_VND));

                    if (acceptsOData)
                    {
                        // OData JSON Request; i.e. Accept header equals: application/json;odata=[verbose, etc]
                        return false;
                    }

                    // consumer asked for JSON but did not indicated SData or OData so default is return SData; just continue
                }
            }

            return true;
        }