dotnet / dotnet/aspnetcore

Adding the raw text input formatter

Open
#49,168 7 comments 1 reaction 0 assignees View on GitHub
api-suggestion area-mvc
Dominant language
C#
Stars
38.4k
Forks
10.9k
Avg merge
2d 6h
Merged PRs (30d)
290

Description

## Background and Motivation

Sometimes we need to read the raw request body as `string` with content-type `text/plain`, it would help us handle these requests more easily

## Proposed API

```csharp
namespace Microsoft.AspNetCore.Mvc.Formatters;

public sealed class RawTextInputFormatter : TextInputFormatter
{
public RawTextInputFormatter()
{
SupportedMediaTypes.Add(MediaTypeHeaderValue.Parse("text/plain"));

SupportedEncodings.Add(Encoding.UTF8);
SupportedEncodings.Add(Encoding.Unicode);
}

public override async Task ReadRequestBodyAsync(InputFormatterContext context, Encoding encoding)
{
using var reader = context.ReaderFactory(context.HttpContext.Request.Body, encoding);
var rawContent = await reader.ReadToEndAsync();
return await InputFormatterResult.SuccessAsync(rawContent);
}
}

```

## Usage Examples

``` csharp
services.AddControllers(options =>
{
options.InputFormatters.Add(new RawTextInputFormatter());
});
```

## Alternative Designs

Maybe also we could use `StringInputFormatter` for the type name since there's a `StringOutputFormatter`, and `PlainTextInputFormatter` can be also treated as a candidate

## Risks

I think it should be fine since it's a new type, since .NET 8 is a major release, maybe we could also include it as one of the default formatters

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.