public void Ctor_AddNameAndQuality_QualityParameterAdded()
 {
     var mediaType = new MediaTypeHeaderValue("application/xml", 0.08);
     Assert.Equal(0.08, mediaType.Quality);
     Assert.Equal("application/xml", mediaType.MediaType);
     Assert.Equal(1, mediaType.Parameters.Count);
 }
        /**
         * TODO: 
         * Refactor ErrorContentResult to ErrorContentResult(string responseType = "json") 
         * and allow JSON & XML responses depending on request type from user.
         */

        public static ContentResult ErrorContentResult(
            object value,
            int status,
            string responseType = "json")
        {
            if (value is string)
            {
                value = new ApiError { Error = value.ToString() };
            }

            string content;
            MediaTypeHeaderValue contentType;
            if (responseType == "xml")
            {
                content = SerializeToJson(value);
                contentType = new MediaTypeHeaderValue("application/xml");
            }
            else
            {
                content = SerializeToJson(value);
                contentType = new MediaTypeHeaderValue("application/json");
            }

            return new ContentResult { StatusCode = status, Content = content, ContentType = contentType };
        }
示例#3
0
        public override bool CanWriteResult([NotNull]OutputFormatterContext context, MediaTypeHeaderValue contentType)
        {
            var type = context.Object.GetType();
            var request = context.ActionContext.HttpContext.Request;

            if (request != null)
            {
                IEdmModel model = request.ODataProperties().Model;
                if (model != null)
                {
                    ODataPayloadKind? payloadKind = null;

                    Type elementType;
                    if (typeof(IEdmObject).GetTypeInfo().IsAssignableFrom(type.GetTypeInfo()) ||
                        (type.IsCollection(out elementType) && typeof(IEdmObject).GetTypeInfo().IsAssignableFrom(elementType.GetTypeInfo())))
                    {
                        payloadKind = GetEdmObjectPayloadKind(type, request);
                    }
                    else
                    {
                        payloadKind = GetClrObjectResponsePayloadKind(type, model, request);
                    }

                    return payloadKind == null ? false : _payloadKinds.Contains(payloadKind.Value);
                }
            }

            return false;
        }
 private static string GetBoundary(MediaTypeHeaderValue contentType) {
     var boundary = HeaderUtilities.RemoveQuotes(contentType.Boundary);
     if(string.IsNullOrWhiteSpace(boundary)) {
         throw new InvalidOperationException("Missing content-type boundary.");
     }
     return boundary;
 }
示例#5
0
        public static void SetFileHeaders(this ResponseHeaders headers,
                                          string fileName, string contentType, bool?inline)
        {
            if (contentType.HasBlackSpace())
            {
                if (MediaTypeHeaderValue.TryParse(contentType, out MediaTypeHeaderValue contentTypeHeader))
                {
                    headers.ContentType = contentTypeHeader;
                }
            }

            if (fileName.HasBlackSpace())
            {
                var dispositionType = GetDispositiontype();
                headers.ContentDisposition = new ContentDispositionHeaderValue(dispositionType)
                {
                    FileName = fileName,
                };

                string GetDispositiontype()
                {
                    if (inline.HasValue)
                    {
                        if (inline.Value)
                        {
                            return("inline");
                        }
                    }

                    return("attachment");
                }
            }
        }
示例#6
0
 private void ValidateContentType(MediaTypeHeaderValue contentType)
 {
     if (contentType.Type == "*" || contentType.SubType == "*")
     {
         throw new ArgumentException(string.Format(Resources.FormatterMappings_NotValidMediaType, contentType));
     }
 }
示例#7
0
        public override async Task ExecuteResultAsync([NotNull] ActionContext context)
        {
            var response = context.HttpContext.Response;

            MediaTypeHeaderValue contentTypeHeader;
            if (string.IsNullOrEmpty(ContentType))
            {
                contentTypeHeader = new MediaTypeHeaderValue("text/plain");
            }
            else
            {
                contentTypeHeader = new MediaTypeHeaderValue(ContentType);
            }

            contentTypeHeader.Encoding = ContentEncoding ?? Encodings.UTF8EncodingWithoutBOM;
            response.ContentType = contentTypeHeader.ToString();

            if (StatusCode != null)
            {
                response.StatusCode = StatusCode.Value;
            }

            if (Content != null)
            {
                await response.WriteAsync(Content, contentTypeHeader.Encoding);
            }
        }
示例#8
0
        /// <inheritdoc />
        public virtual IReadOnlyList<MediaTypeHeaderValue> GetSupportedContentTypes(
            Type declaredType,
            Type runtimeType,
            MediaTypeHeaderValue contentType)
        {
            if (!CanWriteType(declaredType, runtimeType))
            {
                return null;
            }

            if (contentType == null)
            {
                // If contentType is null, then any type we support is valid.
                return _supportedMediaTypes.Count > 0 ? _supportedMediaTypes : null;
            }
            else
            {
                List<MediaTypeHeaderValue> mediaTypes = null;

                foreach (var mediaType in _supportedMediaTypes)
                {
                    if (mediaType.IsSubsetOf(contentType))
                    {
                        if (mediaTypes == null)
                        {
                            mediaTypes = new List<MediaTypeHeaderValue>();
                        }

                        mediaTypes.Add(mediaType);
                    }
                }

                return mediaTypes;
            }
        }
        public async static Task ReturnScript(HttpContext context, string scriptKey, string contentType)
        {
            var dynamicScript = DynamicScriptManager.GetScript(scriptKey);
            if (dynamicScript == null)
            {
                context.Response.StatusCode = (int)HttpStatusCode.NotFound;
                await context.Response.WriteAsync("File not found!");
            }

            var mediaType = new MediaTypeHeaderValue(contentType);
            mediaType.Encoding = System.Text.Encoding.UTF8;
            context.Response.ContentType = mediaType.ToString();

            var responseHeaders = context.Response.GetTypedHeaders();
            var cacheControl = responseHeaders.CacheControl = new CacheControlHeaderValue();
            cacheControl.MaxAge = TimeSpan.FromDays(365);
            cacheControl.Private = true;
            cacheControl.MustRevalidate = false;

            var supportsGzip = dynamicScript.CompressedBytes != null &&
                context.Request.GetTypedHeaders().AcceptEncoding.ToString()
                    .IndexOf("gzip", StringComparison.OrdinalIgnoreCase) >= 0;

            byte[] contentBytes;
            if (supportsGzip)
            {
                context.Response.Headers["Content-Encoding"] = "gzip";
                contentBytes = dynamicScript.CompressedBytes;
            }
            else
                contentBytes = dynamicScript.UncompressedBytes;

            await WriteWithIfModifiedSinceControl(context, contentBytes, dynamicScript.Time);
        }
示例#10
0
        /// <summary>
        /// Asynchronously renders the specified <paramref name="view"/> to the response body.
        /// </summary>
        /// <param name="view">The <see cref="IView"/> to render.</param>
        /// <param name="actionContext">The <see cref="ActionContext"/> for the current executing action.</param>
        /// <param name="viewData">The <see cref="ViewDataDictionary"/> for the view being rendered.</param>
        /// <param name="tempData">The <see cref="ITempDataDictionary"/> for the view being rendered.</param>
        /// <returns>A <see cref="Task"/> that represents the asynchronous rendering.</returns>
        public static async Task ExecuteAsync([NotNull] IView view,
                                              [NotNull] ActionContext actionContext,
                                              [NotNull] ViewDataDictionary viewData,
                                              [NotNull] ITempDataDictionary tempData,
                                              [NotNull] HtmlHelperOptions htmlHelperOptions,
                                              MediaTypeHeaderValue contentType)
        {
            var response = actionContext.HttpContext.Response;

            contentType = contentType ?? DefaultContentType;
            if (contentType.Encoding == null)
            {
                // Do not modify the user supplied content type, so copy it instead
                contentType = contentType.Copy();
                contentType.Encoding = Encoding.UTF8;
            }

            response.ContentType = contentType.ToString();

            using (var writer = new HttpResponseStreamWriter(response.Body, contentType.Encoding))
            {
                var viewContext = new ViewContext(
                    actionContext,
                    view,
                    viewData,
                    tempData,
                    writer,
                    htmlHelperOptions);

                await view.RenderAsync(viewContext);
            }
        }
 public TwilioResponseResult(Action<TwilioResponse> buildResponse)
 {
     var response = new TwilioResponse();
     buildResponse(response);
     Content = response.Element.ToString();
     ContentType = new MediaTypeHeaderValue("text/xml");
 }
 public void Ctor_MediaTypeValidFormat_SuccessfullyCreated()
 {
     var mediaType = new MediaTypeHeaderValue("text/plain");
     Assert.Equal("text/plain", mediaType.MediaType);
     Assert.Equal(0, mediaType.Parameters.Count);
     Assert.Null(mediaType.Charset);
 }
        public void MediaType_SetAndGetMediaType_MatchExpectations()
        {
            var mediaType = new MediaTypeHeaderValue("text/plain");
            Assert.Equal("text/plain", mediaType.MediaType);

            mediaType.MediaType = "application/xml";
            Assert.Equal("application/xml", mediaType.MediaType);
        }
示例#14
0
        /// <summary>
        /// Creates a new <see cref="FileResult"/> instance with
        /// the provided <paramref name="contentType"/>.
        /// </summary>
        /// <param name="contentType">The Content-Type header of the response.</param>
        protected FileResult(MediaTypeHeaderValue contentType)
        {
            if (contentType == null)
            {
                throw new ArgumentNullException(nameof(contentType));
            }

            ContentType = contentType;
        }
 public void Copy_SimpleMediaType_Copied()
 {
     var mediaType0 = new MediaTypeHeaderValue("text/plain");
     var mediaType1 = mediaType0.Copy();
     Assert.NotSame(mediaType0, mediaType1);
     Assert.Same(mediaType0.MediaType, mediaType1.MediaType);
     Assert.NotSame(mediaType0.Parameters, mediaType1.Parameters);
     Assert.Equal(mediaType0.Parameters.Count, mediaType1.Parameters.Count);
 }
示例#16
0
        /// <summary>
        /// Creates a new <see cref="FileContentResult"/> instance with
        /// the provided <paramref name="fileContents"/> and the
        /// provided <paramref name="contentType"/>.
        /// </summary>
        /// <param name="fileContents">The bytes that represent the file contents.</param>
        /// <param name="contentType">The Content-Type header of the response.</param>
        public FileContentResult(byte[] fileContents, MediaTypeHeaderValue contentType)
            : base(contentType?.ToString())
        {
            if (fileContents == null)
            {
                throw new ArgumentNullException(nameof(fileContents));
            }

            FileContents = fileContents;
        }
        public void GetT_KnownTypeWithValidValue_Success()
        {
            var headers = new HeaderDictionary();
            headers[HeaderNames.ContentType] = "text/plain";

            var result = headers.Get<MediaTypeHeaderValue>(HeaderNames.ContentType);

            var expected = new MediaTypeHeaderValue("text/plain");
            Assert.Equal(expected, result);
        }
示例#18
0
        /// <summary>
        /// Creates a new <see cref="PhysicalFileResult"/> instance with
        /// the provided <paramref name="fileName"/> and the provided <paramref name="contentType"/>.
        /// </summary>
        /// <param name="fileName">The path to the file. The path must be an absolute path.</param>
        /// <param name="contentType">The Content-Type header of the response.</param>
        public PhysicalFileResult(string fileName, MediaTypeHeaderValue contentType)
            : base(contentType?.ToString())
        {
            if (fileName == null)
            {
                throw new ArgumentNullException(nameof(fileName));
            }

            FileName = fileName;
        }
示例#19
0
        /// <summary>
        /// Creates a new <see cref="FileStreamResult"/> instance with
        /// the provided <paramref name="fileStream"/> and the
        /// provided <paramref name="contentType"/>.
        /// </summary>
        /// <param name="fileStream">The stream with the file.</param>
        /// <param name="contentType">The Content-Type header of the response.</param>
        public FileStreamResult(Stream fileStream, MediaTypeHeaderValue contentType)
            : base(contentType?.ToString())
        {
            if (fileStream == null)
            {
                throw new ArgumentNullException(nameof(fileStream));
            }

            FileStream = fileStream;
        }
        public void GetT_KnownTypeWithValidValue_Success()
        {
            var context = new DefaultHttpContext();
            context.Request.Headers[HeaderNames.ContentType] = "text/plain";

            var result = context.Request.GetTypedHeaders().Get<MediaTypeHeaderValue>(HeaderNames.ContentType);

            var expected = new MediaTypeHeaderValue("text/plain");
            Assert.Equal(expected, result);
        }
        /// <inheritdoc />
        public bool CanWriteResult([NotNull] OutputFormatterContext context, MediaTypeHeaderValue contentType)
        {
            // Ignore the passed in content type, if the object is a Stream.
            if (context.Object is Stream)
            {
                context.SelectedContentType = contentType;
                return true;
            }

            return false;
        }
示例#22
0
 public override bool CanWriteResult(OutputFormatterContext context, MediaTypeHeaderValue contentType)
 {
     if (base.CanWriteResult(context, contentType))
     {
         var actionReturnString = context.Object as string;
         if (actionReturnString != null)
         {
             return true;
         }
     }
     return false;
 }
        public bool CanWriteResult(OutputFormatterContext context, MediaTypeHeaderValue contentType)
        {
            // ignore the contentType and just look at the content.
            // This formatter will be selected if the content is null.
            // We check for Task as a user can directly create an ObjectContentResult with the unwrapped type.
            if (context.DeclaredType == typeof(void) || context.DeclaredType == typeof(Task))
            {
                return true;
            }

            return TreatNullValueAsNoContent && context.Object == null;
        }
        public void Charset_SetCharsetAndValidateObject_ParametersEntryForCharsetAdded()
        {
            var mediaType = new MediaTypeHeaderValue("text/plain");
            mediaType.Charset = "mycharset";
            Assert.Equal("mycharset", mediaType.Charset);
            Assert.Equal(1, mediaType.Parameters.Count);
            Assert.Equal("charset", mediaType.Parameters.First().Name);

            mediaType.Charset = null;
            Assert.Null(mediaType.Charset);
            Assert.Equal(0, mediaType.Parameters.Count);
            mediaType.Charset = null; // It's OK to set it again to null; no exception.
        }
        public void CopyAsReadOnly_SimpleMediaType_CopiedAndReadOnly()
        {
            var mediaType0 = new MediaTypeHeaderValue("text/plain");
            var mediaType1 = mediaType0.CopyAsReadOnly();
            Assert.NotSame(mediaType0, mediaType1);
            Assert.Same(mediaType0.MediaType, mediaType1.MediaType);
            Assert.NotSame(mediaType0.Parameters, mediaType1.Parameters);
            Assert.Equal(mediaType0.Parameters.Count, mediaType1.Parameters.Count);

            Assert.False(mediaType0.IsReadOnly);
            Assert.True(mediaType1.IsReadOnly);
            Assert.Throws<InvalidOperationException>(() => { mediaType1.MediaType = "some/value"; });
        }
示例#26
0
 public override bool CanWriteResult(OutputFormatterContext context, MediaTypeHeaderValue contentType)
 {
     if (base.CanWriteResult(context, contentType))
     {
         var actionReturn = context.Object as Product;
         if (actionReturn != null)
         {
             var response = context.ActionContext.HttpContext.Response;
             context.SelectedContentType = contentType;
             return true;
         }
     }
     return false;
 }
 /// <summary>
 /// Validates whether action result ContentTypes contains the provided content type from action result containing such property.
 /// </summary>
 /// <param name="actionResult">Action result with ContentTypes.</param>
 /// <param name="expectedContentType">Expected content type.</param>
 /// <param name="failedValidationAction">Action to call in case of failed validation.</param>
 public static void ValidateContainingOfContentType(
     dynamic actionResult,
     MediaTypeHeaderValue expectedContentType,
     Action<string, string, string> failedValidationAction)
 {
     var contentTypes = (MediaTypeCollection)TryGetContentTypesCollection(actionResult);
     if (!contentTypes.Contains(expectedContentType.MediaType))
     {
         failedValidationAction(
             "content types",
             $"to contain {expectedContentType.MediaType}",
             "such was not found");
     }
 }
示例#28
0
        /// <summary>
        /// Sets mapping for the format to specified <see cref="MediaTypeHeaderValue"/>. 
        /// If the format already exists, the <see cref="MediaTypeHeaderValue"/> will be overwritten with the new value.
        /// </summary>
        /// <param name="format">The format value.</param>
        /// <param name="contentType">The <see cref="MediaTypeHeaderValue"/> for the format value.</param>
        public void SetMediaTypeMappingForFormat(string format, MediaTypeHeaderValue contentType)
        {
            if (format == null)
            {
                throw new ArgumentNullException(nameof(format));
            }

            if (contentType == null)
            {
                throw new ArgumentNullException(nameof(contentType));
            }

            ValidateContentType(contentType);
            format = RemovePeriodIfPresent(format);
            _map[format] = contentType.CopyAsReadOnly();
        }
        public override bool CanWriteResult(OutputFormatterContext context, MediaTypeHeaderValue contentType)
        {
            // Ignore the passed in content type, if the object is string
            // always return it as a text/plain format.
            if (context.DeclaredType == typeof(string))
            {
                return true;
            }

            if (context.Object is string)
            {
                return true;
            }

            return false;
        }
        public void CanWriteResult_OnlyActsOnStreams(Type type)
        {
            // Arrange
            var formatter = new StreamOutputFormatter();
            var context = new OutputFormatterContext();
            var contentType = new MediaTypeHeaderValue("text/plain");

            context.Object = type != null ? Activator.CreateInstance(type) : null;

            // Act
            var result = formatter.CanWriteResult(context, contentType);

            // Assert
            Assert.False(result);
            Assert.Null(context.SelectedContentType);
        }
示例#31
0
        /// <summary>
        /// Asynchronously renders the specified <paramref name="view"/> to the response body.
        /// </summary>
        /// <param name="view">The <see cref="IView"/> to render.</param>
        /// <param name="actionContext">The <see cref="ActionContext"/> for the current executing action.</param>
        /// <param name="viewData">The <see cref="ViewDataDictionary"/> for the view being rendered.</param>
        /// <param name="tempData">The <see cref="ITempDataDictionary"/> for the view being rendered.</param>
        /// <returns>A <see cref="Task"/> that represents the asynchronous rendering.</returns>
        public static async Task ExecuteAsync([NotNull] IView view,
                                              [NotNull] ActionContext actionContext,
                                              [NotNull] ViewDataDictionary viewData,
                                              [NotNull] ITempDataDictionary tempData,
                                              [NotNull] HtmlHelperOptions htmlHelperOptions,
                                              MediaTypeHeaderValue contentType)
        {
            var response = actionContext.HttpContext.Response;

            var contentTypeHeader = contentType;
            Encoding encoding;
            if (contentTypeHeader == null)
            {
                contentTypeHeader = DefaultContentType;
                encoding = Encodings.UTF8EncodingWithoutBOM;
            }
            else
            {
                if (contentTypeHeader.Encoding == null)
                {
                    // 1. Do not modify the user supplied content type
                    // 2. Parse here to handle parameters apart from charset
                    contentTypeHeader = MediaTypeHeaderValue.Parse(contentTypeHeader.ToString());
                    contentTypeHeader.Encoding = Encodings.UTF8EncodingWithoutBOM;

                    encoding = Encodings.UTF8EncodingWithoutBOM;
                }
                else
                {
                    encoding = contentTypeHeader.Encoding;
                }
            }

            response.ContentType = contentTypeHeader.ToString();

            using (var writer = new HttpResponseStreamWriter(response.Body, encoding))
            {
                var viewContext = new ViewContext(
                    actionContext,
                    view,
                    viewData,
                    tempData,
                    writer,
                    htmlHelperOptions);

                await view.RenderAsync(viewContext);            }
        }
        public static string GetBoundary(Microsoft.Net.Http.Headers.MediaTypeHeaderValue contentType, int lengthLimit)
        {
            var boundary = HeaderUtilities.RemoveQuotes(contentType.Boundary);

            if (string.IsNullOrWhiteSpace(boundary.ToString()))
            {
                throw new InvalidDataException("Missing content-type boundary.");
            }

            if (boundary.Length > lengthLimit)
            {
                throw new InvalidDataException(
                          $"Multipart boundary length limit {lengthLimit} exceeded.");
            }

            return(boundary.ToString());
        }
示例#33
0
        private async IAsyncEnumerable <Stream> ReadMultipartResponseAsStreamsAsync(HttpContent httpContent, [EnumeratorCancellation] CancellationToken cancellationToken = default)
        {
            EnsureArg.IsNotNull(httpContent, nameof(httpContent));

            await using Stream stream = await httpContent.ReadAsStreamAsync()
                                        .ConfigureAwait(false);

            MultipartSection part;

            var media           = MediaTypeHeaderValue.Parse(httpContent.Headers.ContentType.ToString());
            var multipartReader = new MultipartReader(HeaderUtilities.RemoveQuotes(media.Boundary).Value, stream, 100);

            while ((part = await multipartReader.ReadNextSectionAsync(cancellationToken).ConfigureAwait(false)) != null)
            {
                MemoryStream memoryStream = GetMemoryStream();
                await part.Body.CopyToAsync(memoryStream, cancellationToken).ConfigureAwait(false);

                memoryStream.Seek(0, SeekOrigin.Begin);

                yield return(memoryStream);
            }
        }
        public async Task GivenInstanceWithFrames_WhenRetrieveRequestForFrameInInstance_ValidateReturnedHeaders(params int[] frames)
        {
            (InstanceIdentifier identifier, DicomFile file) = await CreateAndStoreDicomFile(2);

            var requestUri = new Uri(string.Format(DicomWebConstants.BaseRetrieveFramesUriFormat, identifier.StudyInstanceUid, identifier.SeriesInstanceUid, identifier.SopInstanceUid, string.Join("%2C", frames)), UriKind.Relative);

            using (var request = new HttpRequestMessage(HttpMethod.Get, requestUri))
            {
                // Set accept header to multipart/related; type="application/octet-stream"
                MediaTypeWithQualityHeaderValue multipartHeader = new MediaTypeWithQualityHeaderValue(KnownContentTypes.MultipartRelated);
                NameValueHeaderValue            contentHeader   = new NameValueHeaderValue("type", "\"" + KnownContentTypes.ApplicationOctetStream + "\"");
                multipartHeader.Parameters.Add(contentHeader);

                string transferSyntaxHeader = ";transfer-syntax=\"*\"";
                request.Headers.TryAddWithoutValidation("Accept", $"{multipartHeader.ToString()}{transferSyntaxHeader}");

                request.Headers.Add("transfer-syntax", "*");

                using (HttpResponseMessage response = await _client.HttpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, _defaultCancellationToken))
                {
                    Assert.True(response.IsSuccessStatusCode);

                    await using (Stream stream = await response.Content.ReadAsStreamAsync())
                    {
                        // Open stream in response message's content and read using multipart reader.
                        MultipartSection part;
                        var media           = MediaTypeHeaderValue.Parse(response.Content.Headers.ContentType.ToString());
                        var multipartReader = new MultipartReader(HeaderUtilities.RemoveQuotes(media.Boundary).Value, stream, 100);

                        while ((part = await multipartReader.ReadNextSectionAsync(_defaultCancellationToken)) != null)
                        {
                            // Validate header on individual parts is application/octet-stream.
                            Assert.Equal(KnownContentTypes.ApplicationOctetStream, part.ContentType);
                        }
                    }
                }
            }
        }
示例#35
0
        private async Task <IEnumerable <Stream> > ReadMultipartResponseAsStreamsAsync(HttpContent httpContent, CancellationToken cancellationToken)
        {
            EnsureArg.IsNotNull(httpContent, nameof(httpContent));

            var result = new List <Stream>();

            await using (Stream stream = await httpContent.ReadAsStreamAsync())
            {
                MultipartSection part;
                var media           = MediaTypeHeaderValue.Parse(httpContent.Headers.ContentType.ToString());
                var multipartReader = new MultipartReader(HeaderUtilities.RemoveQuotes(media.Boundary).Value, stream, 100);

                while ((part = await multipartReader.ReadNextSectionAsync(cancellationToken)) != null)
                {
                    var memoryStream = GetMemoryStream();
                    await part.Body.CopyToAsync(memoryStream, cancellationToken);

                    memoryStream.Seek(0, SeekOrigin.Begin);
                    result.Add(memoryStream);
                }
            }

            return(result);
        }
示例#36
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ApiHeaders"/> class.
        /// </summary>
        /// <param name="requestHeaders">The <see cref="RequestHeaders"/> containing the serialized <see cref="ApiHeaders"/>.</param>
        /// <param name="ignoreMissingAuth">If a missing <see cref="HeaderNames.Authorization"/> should be ignored.</param>
        /// <exception cref="HeadersException">Thrown if the <paramref name="requestHeaders"/> constitue invalid <see cref="ApiHeaders"/>.</exception>
#pragma warning disable CA1502
        public ApiHeaders(RequestHeaders requestHeaders, bool ignoreMissingAuth = false)
        {
            if (requestHeaders == null)
            {
                throw new ArgumentNullException(nameof(requestHeaders));
            }

            var badHeaders   = HeaderTypes.None;
            var errorBuilder = new StringBuilder();

            void AddError(HeaderTypes headerType, string message)
            {
                if (badHeaders != HeaderTypes.None)
                {
                    errorBuilder.AppendLine();
                }
                badHeaders |= headerType;
                errorBuilder.Append(message);
            }

            var jsonAccept = new Microsoft.Net.Http.Headers.MediaTypeHeaderValue(MediaTypeNames.Application.Json);

            if (!requestHeaders.Accept.Any(x => jsonAccept.IsSubsetOf(x)))
            {
                AddError(HeaderTypes.Accept, $"Client does not accept {MediaTypeNames.Application.Json}!");
            }

            if (!requestHeaders.Headers.TryGetValue(HeaderNames.UserAgent, out var userAgentValues) || userAgentValues.Count == 0)
            {
                AddError(HeaderTypes.UserAgent, $"Missing {HeaderNames.UserAgent} header!");
            }
            else
            {
                RawUserAgent = userAgentValues.First();
                if (String.IsNullOrWhiteSpace(RawUserAgent))
                {
                    AddError(HeaderTypes.UserAgent, $"Malformed {HeaderNames.UserAgent} header!");
                }
            }

            // make sure the api header matches ours
            Version?apiVersion = null;

            if (!requestHeaders.Headers.TryGetValue(ApiVersionHeader, out var apiUserAgentHeaderValues) || !ProductInfoHeaderValue.TryParse(apiUserAgentHeaderValues.FirstOrDefault(), out var apiUserAgent) || apiUserAgent.Product.Name != AssemblyName.Name)
            {
                AddError(HeaderTypes.Api, $"Missing {ApiVersionHeader} header!");
            }
            else if (!Version.TryParse(apiUserAgent.Product.Version, out apiVersion))
            {
                AddError(HeaderTypes.Api, $"Malformed {ApiVersionHeader} header!");
            }

            if (!requestHeaders.Headers.TryGetValue(HeaderNames.Authorization, out StringValues authorization))
            {
                if (!ignoreMissingAuth)
                {
                    AddError(HeaderTypes.Authorization, $"Missing {HeaderNames.Authorization} header!");
                }
            }
            else
            {
                var auth   = authorization.First();
                var splits = new List <string>(auth.Split(' '));
                var scheme = splits.First();
                if (String.IsNullOrWhiteSpace(scheme))
                {
                    AddError(HeaderTypes.Authorization, "Missing authentication scheme!");
                }
                else
                {
                    splits.RemoveAt(0);
                    var parameter = String.Concat(splits);
                    if (String.IsNullOrEmpty(parameter))
                    {
                        AddError(HeaderTypes.Authorization, "Missing authentication parameter!");
                    }
                    else
                    {
                        if (requestHeaders.Headers.TryGetValue(InstanceIdHeader, out var instanceIdValues))
                        {
                            var instanceIdString = instanceIdValues.FirstOrDefault();
                            if (instanceIdString != default && Int64.TryParse(instanceIdString, out var instanceId))
                            {
                                InstanceId = instanceId;
                            }
                        }

                        switch (scheme)
                        {
                        case OAuthAuthenticationScheme:
                            if (requestHeaders.Headers.TryGetValue(OAuthProviderHeader, out StringValues oauthProviderValues))
                            {
                                var oauthProviderString = oauthProviderValues.First();
                                if (Enum.TryParse <OAuthProvider>(oauthProviderString, out var oauthProvider))
                                {
                                    OAuthProvider = oauthProvider;
                                }
                                else
                                {
                                    AddError(HeaderTypes.OAuthProvider, "Invalid OAuth provider!");
                                }
                            }
                            else
                            {
                                AddError(HeaderTypes.OAuthProvider, $"Missing {OAuthProviderHeader} header!");
                            }

                            goto case BearerAuthenticationScheme;

                        case BearerAuthenticationScheme:
                            Token = parameter;
                            break;

                        case BasicAuthenticationScheme:
                            string badBasicAuthHeaderMessage = $"Invalid basic {HeaderNames.Authorization} header!";
                            string joinedString;
                            try
                            {
                                var base64Bytes = Convert.FromBase64String(parameter);
                                joinedString = Encoding.UTF8.GetString(base64Bytes);
                            }
                            catch
                            {
                                AddError(HeaderTypes.Authorization, badBasicAuthHeaderMessage);
                                break;
                            }

                            var basicAuthSplits = joinedString.Split(new char[] { ':' }, StringSplitOptions.RemoveEmptyEntries);
                            if (basicAuthSplits.Length < 2)
                            {
                                AddError(HeaderTypes.Authorization, badBasicAuthHeaderMessage);
                                break;
                            }

                            Username = basicAuthSplits.First();
                            Password = String.Concat(basicAuthSplits.Skip(1));
                            break;

                        default:
                            AddError(HeaderTypes.Authorization, "Invalid authentication scheme!");
                            break;
                        }
                    }
                }
            }

            if (badHeaders != HeaderTypes.None)
            {
                throw new HeadersException(badHeaders, errorBuilder.ToString());
            }

            ApiVersion = apiVersion !.Semver();
        }
示例#37
0
        /// <summary>
        /// Construct and validates <see cref="ApiHeaders"/> from a set of <paramref name="requestHeaders"/>
        /// </summary>
        /// <param name="requestHeaders">The <see cref="RequestHeaders"/> containing the <see cref="ApiHeaders"/></param>
        public ApiHeaders(RequestHeaders requestHeaders)
        {
            if (requestHeaders == null)
            {
                throw new ArgumentNullException(nameof(requestHeaders));
            }

            var jsonAccept = new Microsoft.Net.Http.Headers.MediaTypeHeaderValue(ApplicationJson);

            if (!requestHeaders.Accept.Any(x => x.MediaType == jsonAccept.MediaType))
            {
                throw new InvalidOperationException(String.Format(CultureInfo.InvariantCulture, "Client does not accept {0}!", ApplicationJson));
            }

            if (!requestHeaders.Headers.TryGetValue(HeaderNames.UserAgent, out var userAgentValues) || userAgentValues.Count == 0)
            {
                throw new InvalidOperationException(String.Format(CultureInfo.InvariantCulture, "Missing {0} headers!", HeaderNames.UserAgent));
            }

            RawUserAgent = userAgentValues.First();
            if (String.IsNullOrWhiteSpace(RawUserAgent))
            {
                throw new InvalidOperationException("Malformed client User-Agent!");
            }

            // make sure the api header matches ours
            if (!requestHeaders.Headers.TryGetValue(ApiVersionHeader, out var apiUserAgentHeaderValues) || !ProductInfoHeaderValue.TryParse(apiUserAgentHeaderValues.FirstOrDefault(), out var apiUserAgent) || apiUserAgent.Product.Name != AssemblyName.Name)
            {
                throw new InvalidOperationException("Missing API version!");
            }

            if (!Version.TryParse(apiUserAgent.Product.Version, out var apiVersion))
            {
                throw new InvalidOperationException("Malformed API version!");
            }

            ApiVersion = apiVersion.Semver();

            if (!requestHeaders.Headers.TryGetValue(HeaderNames.Authorization, out StringValues authorization))
            {
                throw new InvalidOperationException(String.Format(CultureInfo.InvariantCulture, "Missing {0} header!", HeaderNames.Authorization));
            }
            var auth   = authorization.First();
            var splits = new List <string>(auth.Split(' '));
            var scheme = splits.First();

            if (String.IsNullOrWhiteSpace(scheme))
            {
                throw new InvalidOperationException("Missing authentication scheme!");
            }

            splits.RemoveAt(0);
            var parameter = String.Concat(splits);

            if (String.IsNullOrEmpty(parameter))
            {
                throw new InvalidOperationException("Missing authentication parameter!");
            }

            if (requestHeaders.Headers.TryGetValue(InstanceIdHeader, out var instanceIdValues))
            {
                var instanceIdString = instanceIdValues.FirstOrDefault();
                if (instanceIdString != default && Int64.TryParse(instanceIdString, out var instanceId))
                {
                    InstanceId = instanceId;
                }
            }

#pragma warning disable CA1308 // Normalize strings to uppercase
            switch (scheme.ToLowerInvariant())
#pragma warning restore CA1308 // Normalize strings to uppercase
            {
            case JwtAuthenticationScheme:
                Token = parameter;
                break;

            case PasswordAuthenticationScheme:
                Password = parameter;
                var fail = !requestHeaders.Headers.TryGetValue(UsernameHeader, out var values);
                if (!fail)
                {
                    Username = values.FirstOrDefault();
                    fail     = String.IsNullOrWhiteSpace(Username);
                }

                if (fail)
                {
                    throw new InvalidOperationException("Missing Username header!");
                }
                break;

            case BasicAuthenticationScheme:
                string joinedString;
                try
                {
                    var base64Bytes = Convert.FromBase64String(parameter);
                    joinedString = Encoding.UTF8.GetString(base64Bytes);
                }
                catch
                {
                    throw new InvalidOperationException("Invalid basic Authorization header!");
                }

                var basicAuthSplits = joinedString.Split(new char[] { ':' }, StringSplitOptions.RemoveEmptyEntries);
                if (basicAuthSplits.Length < 2)
                {
                    throw new InvalidOperationException("Invalid basic Authorization header!");
                }

                Username = basicAuthSplits.First();
                Password = String.Concat(basicAuthSplits.Skip(1));
                break;

            default:
                throw new InvalidOperationException("Invalid authentication scheme!");
            }
        }
示例#38
0
        /// <summary>
        /// Construct and validates <see cref="ApiHeaders"/> from a set of <paramref name="requestHeaders"/>
        /// </summary>
        /// <param name="requestHeaders">The <see cref="RequestHeaders"/> containing the <see cref="ApiHeaders"/></param>
        public ApiHeaders(RequestHeaders requestHeaders)
        {
            var jsonAccept = new Microsoft.Net.Http.Headers.MediaTypeHeaderValue(ApplicationJson);

            if (!requestHeaders.Accept.Any(x => x.MediaType == jsonAccept.MediaType))
            {
                throw new InvalidOperationException(String.Format(CultureInfo.InvariantCulture, "Client does not accept {0}!", ApplicationJson));
            }

            if (!requestHeaders.Headers.TryGetValue(HeaderNames.UserAgent, out var userAgentValues) || !ProductInfoHeaderValue.TryParse(userAgentValues.FirstOrDefault(), out var clientUserAgent))
            {
                throw new InvalidOperationException(String.Format(CultureInfo.InvariantCulture, "Missing {0} headers!", HeaderNames.UserAgent));
            }

            // assure the client user agent has a name and version
            if (String.IsNullOrWhiteSpace(clientUserAgent.Product.Name) || !Version.TryParse(clientUserAgent.Product.Version, out var clientVersion))
            {
                throw new InvalidOperationException("Malformed client user agent!");
            }

            // make sure the api header matches ours
            if (!requestHeaders.Headers.TryGetValue(ApiVersionHeader, out var apiUserAgentHeaderValues) || !ProductInfoHeaderValue.TryParse(apiUserAgentHeaderValues.FirstOrDefault(), out var apiUserAgent) || apiUserAgent.Product.Name != AssemblyName.Name)
            {
                throw new InvalidOperationException("Missing API version!");
            }

            if (!Version.TryParse(apiUserAgent.Product.Version, out var apiVersion))
            {
                throw new InvalidOperationException("Malformed API version!");
            }

            ApiVersion = apiVersion;
            UserAgent  = clientUserAgent.Product;

            if (!requestHeaders.Headers.TryGetValue(HeaderNames.Authorization, out StringValues authorization))
            {
                throw new InvalidOperationException(String.Format(CultureInfo.InvariantCulture, "Missing {0} header!", HeaderNames.Authorization));
            }
            var auth   = authorization.First();
            var splits = new List <string>(auth.Split(' '));
            var scheme = splits.First();

            if (String.IsNullOrWhiteSpace(scheme))
            {
                throw new InvalidOperationException("Missing authentication scheme!");
            }

            splits.RemoveAt(0);
            var parameter = String.Concat(splits);

            if (String.IsNullOrEmpty(parameter))
            {
                throw new InvalidOperationException("Missing authentication parameter!");
            }

            if (requestHeaders.Headers.TryGetValue(InstanceIdHeader, out var instanceIdValues))
            {
                var instanceIdString = instanceIdValues.FirstOrDefault();
                if (instanceIdString != default && Int64.TryParse(instanceIdString, out var instanceId))
                {
                    InstanceId = instanceId;
                }
            }

            switch (scheme)
            {
            case JwtAuthenticationScheme:
                Token = parameter;
                break;

            case PasswordAuthenticationScheme:
                Password = parameter;
                var fail = !requestHeaders.Headers.TryGetValue(UsernameHeader, out var values);
                if (!fail)
                {
                    Username = values.FirstOrDefault();
                    fail     = String.IsNullOrWhiteSpace(Username);
                }

                if (fail)
                {
                    throw new InvalidOperationException("Missing Username header!");
                }
                break;

            default:
                throw new InvalidOperationException("Invalid authentication scheme!");
            }
        }
示例#39
0
 public CsvOutputFormatter()
 {
     SupportedMediaTypes.Add(MediaTypeHeaderValue.Parse("text/csv"));
     SupportedEncodings.Add(Encoding.UTF8);
     SupportedEncodings.Add(Encoding.Unicode);
 }