// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Linq;
using System.Net.Http.Headers;
using System.Web.Http;
namespace System.Net.Http.Formatting
{
///
/// A that maps the X-Requested-With http header field set by AJAX XmlHttpRequest (XHR)
/// to the media type application/json if no explicit Accept header fields are present in the request.
///
public class XmlHttpRequestHeaderMapping : RequestHeaderMapping
{
///
/// Initializes a new instance of class
///
public XmlHttpRequestHeaderMapping() :
base(FormattingUtilities.HttpRequestedWithHeader, FormattingUtilities.HttpRequestedWithHeaderValue, StringComparison.OrdinalIgnoreCase, isValueSubstring: true, mediaType: MediaTypeConstants.ApplicationJsonMediaType)
{
}
///
/// Returns a value indicating whether the current
/// instance can return a from .
///
/// The to check.
///
/// The quality of the match.
/// A value of 0.0 signifies no match.
/// A value of 1.0 signifies a complete match and that the request was made using XmlHttpRequest without an Accept header.
///
public override double TryMatchMediaType(HttpRequestMessage request)
{
if (request == null)
{
throw Error.ArgumentNull("request");
}
// Accept header trumps XHR mapping.
// Accept: */* is equivalent to passing no Accept header.
if (request.Headers.Accept.Count == 0
|| (request.Headers.Accept.Count == 1 && request.Headers.Accept.First().MediaType.Equals("*/*", StringComparison.Ordinal)))
{
return base.TryMatchMediaType(request);
}
else
{
return FormattingUtilities.NoMatch;
}
}
}
}