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
/
StringOutputFormatter.cs
61 lines (52 loc) · 1.88 KB
/
StringOutputFormatter.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
// 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.Http;
namespace Microsoft.AspNetCore.Mvc.Formatters
{
/// <summary>
/// A <see cref="TextOutputFormatter"/> for simple text content.
/// </summary>
public class StringOutputFormatter : TextOutputFormatter
{
public StringOutputFormatter()
{
SupportedEncodings.Add(Encoding.UTF8);
SupportedEncodings.Add(Encoding.Unicode);
SupportedMediaTypes.Add("text/plain");
}
public override bool CanWriteResult(OutputFormatterCanWriteContext context)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
if (context.ObjectType == typeof(string) || context.Object is string)
{
// Call into base to check if the current request's content type is a supported media type.
return base.CanWriteResult(context);
}
return false;
}
public override Task WriteResponseBodyAsync(OutputFormatterWriteContext context, Encoding encoding)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
if (encoding == null)
{
throw new ArgumentNullException(nameof(encoding));
}
var valueAsString = (string)context.Object;
if (string.IsNullOrEmpty(valueAsString))
{
return Task.CompletedTask;
}
var response = context.HttpContext.Response;
return response.WriteAsync(valueAsString, encoding);
}
}
}