// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using Microsoft.AspNet.Mvc.Core; using Microsoft.Net.Http.Headers; namespace Microsoft.AspNet.Mvc { /// /// Used to specify mapping between the URL Format and corresponding . /// public class FormatterMappings { private readonly Dictionary _map = new Dictionary(StringComparer.OrdinalIgnoreCase); /// /// Sets mapping for the format to specified . /// If the format already exists, the will be overwritten with the new value. /// /// The format value. /// The for the format value. public void SetMediaTypeMappingForFormat([NotNull] string format, [NotNull] MediaTypeHeaderValue contentType) { ValidateContentType(contentType); format = RemovePeriodIfPresent(format); _map[format] = MediaTypeHeaderValue.Parse(contentType.ToString()); } /// /// Gets for the specified format. /// /// The format value. /// The for input format. public MediaTypeHeaderValue GetMediaTypeMappingForFormat([NotNull] string format) { format = RemovePeriodIfPresent(format); MediaTypeHeaderValue value = null; _map.TryGetValue(format, out value); return value; } /// /// Clears the mapping for the format. /// /// The format value. /// true if the format is successfully found and cleared; otherwise, false. public bool ClearMediaTypeMappingForFormat([NotNull] string format) { format = RemovePeriodIfPresent(format); return _map.Remove(format); } private void ValidateContentType(MediaTypeHeaderValue contentType) { if (contentType.Type == "*" || contentType.SubType == "*") { throw new ArgumentException(string.Format(Resources.FormatterMappings_NotValidMediaType, contentType)); } } private string RemovePeriodIfPresent(string format) { if (format == "") { throw new ArgumentException(Resources.ArgumentCannotBeNullOrEmpty, "format"); } if (format.StartsWith(".")) { if (format == ".") { throw new ArgumentException(string.Format(Resources.Format_NotValid, format)); } format = format.Substring(1); } return format; } } }