This repository has been archived by the owner on Dec 14, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
ContentResultExecutor.cs
74 lines (61 loc) · 2.75 KB
/
ContentResultExecutor.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
// 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;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc.Internal;
using Microsoft.Extensions.Logging;
namespace Microsoft.AspNetCore.Mvc.Infrastructure
{
public class ContentResultExecutor : IActionResultExecutor<ContentResult>
{
private const string DefaultContentType = "text/plain; charset=utf-8";
private readonly ILogger<ContentResultExecutor> _logger;
private readonly IHttpResponseStreamWriterFactory _httpResponseStreamWriterFactory;
public ContentResultExecutor(ILogger<ContentResultExecutor> logger, IHttpResponseStreamWriterFactory httpResponseStreamWriterFactory)
{
_logger = logger;
_httpResponseStreamWriterFactory = httpResponseStreamWriterFactory;
}
/// <inheritdoc />
public virtual async Task ExecuteAsync(ActionContext context, ContentResult result)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
if (result == null)
{
throw new ArgumentNullException(nameof(result));
}
var response = context.HttpContext.Response;
string resolvedContentType;
Encoding resolvedContentTypeEncoding;
ResponseContentTypeHelper.ResolveContentTypeAndEncoding(
result.ContentType,
response.ContentType,
DefaultContentType,
out resolvedContentType,
out resolvedContentTypeEncoding);
response.ContentType = resolvedContentType;
if (result.StatusCode != null)
{
response.StatusCode = result.StatusCode.Value;
}
_logger.ContentResultExecuting(resolvedContentType);
if (result.Content != null)
{
response.ContentLength = resolvedContentTypeEncoding.GetByteCount(result.Content);
using (var textWriter = _httpResponseStreamWriterFactory.CreateWriter(response.Body, resolvedContentTypeEncoding))
{
await textWriter.WriteAsync(result.Content);
// Flushing the HttpResponseStreamWriter does not flush the underlying stream. This just flushes
// the buffered text in the writer.
// We do this rather than letting dispose handle it because dispose would call Write and we want
// to call WriteAsync.
await textWriter.FlushAsync();
}
}
}
}
}