Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 31 additions & 16 deletions src/Mvc/Mvc.Core/src/Formatters/AcceptHeaderParser.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
// The .NET Foundation licenses this file to you under the MIT license.

using System.Diagnostics;
using Microsoft.Extensions.Primitives;
using Microsoft.Net.Http.Headers;

namespace Microsoft.AspNetCore.Mvc.Formatters;
Expand All @@ -22,28 +23,42 @@ public static void ParseAcceptHeader(IList<string> acceptHeaders, IList<MediaTyp
ArgumentNullException.ThrowIfNull(parsedValues);
for (var i = 0; i < acceptHeaders.Count; i++)
{
var charIndex = 0;
var value = acceptHeaders[i];
ParseAcceptHeaderValue(acceptHeaders[i], parsedValues);
}
}

while (!string.IsNullOrEmpty(value) && charIndex < value.Length)
{
var startCharIndex = charIndex;
// Overload that avoids boxing the StringValues to IList<string>.
public static void ParseAcceptHeader(StringValues acceptHeaders, IList<MediaTypeSegmentWithQuality> parsedValues)
{
ArgumentNullException.ThrowIfNull(parsedValues);
for (var i = 0; i < acceptHeaders.Count; i++)
{
ParseAcceptHeaderValue(acceptHeaders[i], parsedValues);
}
}

if (TryParseValue(value, ref charIndex, out var output))
{
// The entry may not contain an actual value, like Accept: application/json, , */*
if (output.MediaType.HasValue)
{
parsedValues.Add(output);
}
}
private static void ParseAcceptHeaderValue(string? value, IList<MediaTypeSegmentWithQuality> parsedValues)
{
var charIndex = 0;

while (!string.IsNullOrEmpty(value) && charIndex < value.Length)
{
var startCharIndex = charIndex;

if (charIndex <= startCharIndex)
if (TryParseValue(value, ref charIndex, out var output))
{
// The entry may not contain an actual value, like Accept: application/json, , */*
if (output.MediaType.HasValue)
{
Debug.Fail("ParseAcceptHeader should advance charIndex, this is a bug.");
break;
parsedValues.Add(output);
}
}

if (charIndex <= startCharIndex)
{
Debug.Fail("ParseAcceptHeader should advance charIndex, this is a bug.");
break;
}
}
}

Expand Down
9 changes: 7 additions & 2 deletions src/Mvc/Mvc.Core/src/Formatters/TextOutputFormatter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -170,8 +170,13 @@ public sealed override Task WriteResponseBodyAsync(OutputFormatterWriteContext c

internal static IList<StringWithQualityHeaderValue> GetAcceptCharsetHeaderValues(OutputFormatterWriteContext context)
{
var request = context.HttpContext.Request;
if (StringWithQualityHeaderValue.TryParseList(request.Headers.AcceptCharset, out var result))
var acceptCharset = context.HttpContext.Request.Headers.AcceptCharset;
if (acceptCharset.Count == 0)
{
return Array.Empty<StringWithQualityHeaderValue>();
}

if (StringWithQualityHeaderValue.TryParseList(acceptCharset, out var result))
{
return result;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ public partial class DefaultOutputFormatterSelector : OutputFormatterSelector
return left.Quality > right.Quality ? -1 : (left.Quality == right.Quality ? 0 : 1);
};

private const int MaxInitialAcceptCapacity = 16;
private readonly ILogger _logger;
private readonly IList<IOutputFormatter> _formatters;
private readonly bool _respectBrowserAcceptHeader;
Expand Down Expand Up @@ -146,10 +147,25 @@ public DefaultOutputFormatterSelector(IOptions<MvcOptions> options, ILoggerFacto
return selectedFormatter;
}

private List<MediaTypeSegmentWithQuality> GetAcceptableMediaTypes(HttpRequest request)
private IList<MediaTypeSegmentWithQuality> GetAcceptableMediaTypes(HttpRequest request)
{
var result = new List<MediaTypeSegmentWithQuality>();
AcceptHeaderParser.ParseAcceptHeader(request.Headers.Accept, result);
var acceptHeader = request.Headers.Accept;
if (acceptHeader.Count == 0)
{
return Array.Empty<MediaTypeSegmentWithQuality>();
}

// Pre-size the list using the number of comma separated entries so that the common case of a short Accept
// header does not over-allocate or grow the backing array. The initial capacity is bounded so that headers
// containing many empty entries don't over-allocate; the list grows as needed for longer headers.
var capacity = 0;
for (var i = 0; i < acceptHeader.Count && capacity < MaxInitialAcceptCapacity; i++)
{
capacity += acceptHeader[i] is { } value ? value.AsSpan().Count(',') + 1 : 0;
Comment thread
davidfowl marked this conversation as resolved.
Resolved
}

var result = new List<MediaTypeSegmentWithQuality>(Math.Min(capacity, MaxInitialAcceptCapacity));
AcceptHeaderParser.ParseAcceptHeader(acceptHeader, result);
for (var i = 0; i < result.Count; i++)
{
var mediaType = new MediaType(result[i].MediaType);
Expand All @@ -171,8 +187,9 @@ private List<MediaTypeSegmentWithQuality> GetAcceptableMediaTypes(HttpRequest re
{
Log.SelectFirstCanWriteFormatter(_logger);

foreach (var formatter in formatters)
for (var i = 0; i < formatters.Count; i++)
{
var formatter = formatters[i];
formatterContext.ContentType = new StringSegment();
formatterContext.ContentTypeIsServerDefined = false;

Expand Down Expand Up @@ -215,10 +232,12 @@ private List<MediaTypeSegmentWithQuality> GetAcceptableMediaTypes(HttpRequest re
IList<IOutputFormatter> formatters,
MediaTypeCollection acceptableContentTypes)
{
foreach (var formatter in formatters)
for (var i = 0; i < formatters.Count; i++)
{
foreach (var contentType in acceptableContentTypes)
var formatter = formatters[i];
for (var j = 0; j < acceptableContentTypes.Count; j++)
{
var contentType = acceptableContentTypes[j];
formatterContext.ContentType = new StringSegment(contentType);
formatterContext.ContentTypeIsServerDefined = true;

Expand Down
28 changes: 28 additions & 0 deletions src/Mvc/Mvc.Core/test/Formatters/AcceptHeaderParserTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,34 @@ public void ParseAcceptHeader_ParsesMultipleHeaderValues()
Assert.Equal(expected, parsed);
}

[Fact]
public void ParseAcceptHeader_StringValues_ParsesMultipleHeaderValues()
{
var expected = new List<MediaTypeSegmentWithQuality>
{
new MediaTypeSegmentWithQuality(new StringSegment("application/json"), 1.0),
new MediaTypeSegmentWithQuality(new StringSegment("text/plain;q=0.9"), 0.9),
new MediaTypeSegmentWithQuality(new StringSegment("application/xml;q=0.8"), 0.8)
};
var parsed = new List<MediaTypeSegmentWithQuality>();

AcceptHeaderParser.ParseAcceptHeader(
new StringValues(new[] { "application/json, text/plain;q=0.9", "", null, "application/xml;q=0.8" }),
parsed);

Assert.Equal(expected, parsed);
}

[Fact]
public void ParseAcceptHeader_StringValues_Empty_ParsesNothing()
{
var parsed = new List<MediaTypeSegmentWithQuality>();

AcceptHeaderParser.ParseAcceptHeader(StringValues.Empty, parsed);

Assert.Empty(parsed);
}

// The text "*/*Content-Type" parses as a valid media type value. However it's followed
// by ':' instead of whitespace or a delimiter, which means that it's actually invalid.
[Fact]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -295,6 +295,61 @@ public void SelectFormatter_WithAcceptHeaderOnly_SetsContentTypeIsServerDefinedT
Assert.Null(formatter);
}

[Fact]
public void SelectFormatter_WithMultipleAcceptHeaderValues_SelectsHighestQualityAcrossValues()
{
var formatters = new List<IOutputFormatter>
{
new TestXmlOutputFormatter(),
new TestJsonOutputFormatter(),
};
var selector = CreateSelector(formatters);

var context = new OutputFormatterWriteContext(
new DefaultHttpContext(),
new TestHttpResponseStreamWriterFactory().CreateWriter,
objectType: null,
@object: null);

context.HttpContext.Request.Headers.Accept = new StringValues(new[] { "application/xml;q=0.5", "", "text/plain, application/json" });

var formatter = selector.SelectFormatter(
context,
Array.Empty<IOutputFormatter>(),
new MediaTypeCollection());

Assert.Same(formatters[1], formatter);
Assert.Equal(new StringSegment("application/json"), context.ContentType);
}

[Fact]
public void SelectFormatter_WithEmptyAcceptHeaderValue_ChoosesFirstFormatterThatCanWrite()
{
var formatters = new List<IOutputFormatter>
{
new CannotWriteFormatter(),
new TestJsonOutputFormatter(),
new TestXmlOutputFormatter(),
};
var selector = CreateSelector(formatters);

var context = new OutputFormatterWriteContext(
new DefaultHttpContext(),
new TestHttpResponseStreamWriterFactory().CreateWriter,
objectType: null,
@object: null);

context.HttpContext.Request.Headers.Accept = "";

var formatter = selector.SelectFormatter(
context,
Array.Empty<IOutputFormatter>(),
new MediaTypeCollection());

Assert.Same(formatters[1], formatter);
Assert.Equal(new StringSegment("application/json"), context.ContentType);
}

[Fact]
public void SelectFormatter_WithAcceptHeaderAndContentTypes_SetsContentTypeIsServerDefinedWhenExpected()
{
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using BenchmarkDotNet.Attributes;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.Mvc.Abstractions;
using Microsoft.AspNetCore.Mvc.Formatters;
using Microsoft.AspNetCore.Mvc.Infrastructure;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.Options;

namespace Microsoft.AspNetCore.Mvc.Microbenchmarks;

public class ObjectResultExecutorBenchmark
{
private ObjectResultExecutor _executor;
private ActionContext _actionContext;
private DefaultHttpContext _httpContext;
private ObjectResult _result;

[Params("", "application/json", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")]
public string Accept { get; set; }

[GlobalSetup]
public void Setup()
{
var options = new MvcOptions();
options.OutputFormatters.Add(new HttpNoContentOutputFormatter());
options.OutputFormatters.Add(new StringOutputFormatter());
options.OutputFormatters.Add(new StreamOutputFormatter());
options.OutputFormatters.Add(new SystemTextJsonOutputFormatter(new System.Text.Json.JsonSerializerOptions(System.Text.Json.JsonSerializerDefaults.Web) { TypeInfoResolver = new System.Text.Json.Serialization.Metadata.DefaultJsonTypeInfoResolver() }));

var services = new ServiceCollection().BuildServiceProvider();
var selector = new DefaultOutputFormatterSelector(Options.Create(options), NullLoggerFactory.Instance);
_executor = new ObjectResultExecutor(
selector,
new TestHttpResponseStreamWriterFactory(),
NullLoggerFactory.Instance,
Options.Create(options));

_httpContext = new DefaultHttpContext { RequestServices = services };
_actionContext = new ActionContext(_httpContext, new RouteData(), new ActionDescriptor());
_result = new ObjectResult(new Model { Id = 1, Name = "Hello" });
}

[Benchmark]
public Task Execute()
{
if (Accept.Length == 0)
{
_httpContext.Request.Headers.Remove("Accept");
}
else
{
_httpContext.Request.Headers.Accept = Accept;
}
_httpContext.Response.Headers.Clear();
// Use a fresh response body feature for every invocation so each sample measures the same writer lifecycle.
_httpContext.Features.Set<IHttpResponseBodyFeature>(new StreamResponseBodyFeature(Stream.Null));
return _executor.ExecuteAsync(_actionContext, _result);
}

public class Model
{
public int Id { get; set; }
public string Name { get; set; }
}

private sealed class TestHttpResponseStreamWriterFactory : IHttpResponseStreamWriterFactory
{
public TextWriter CreateWriter(Stream stream, System.Text.Encoding encoding) => new StreamWriter(stream, encoding);
}
}
Loading