I'm trying to write my own Input Formatter which will read the request body, split it by line and pass it into a string array parameter in a controller action.
This works (passing the entire body as a string):
Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddMvcCore(options =>
{
options.InputFormatters.Add(new MyInputFormatter());
}
}
MyInputFormatter.cs
public override async Task<InputFormatterResult> ReadRequestBodyAsync(InputFormatterContext context)
{
using (StreamReader reader = new StreamReader(context.HttpContext.Request.Body))
{
return InputFormatterResult.Success(await reader.ReadToEndAsync());
}
}
MyController.cs
[HttpPost("/foo", Name = "Foo")]
public IActionResult Bar([FromBody] string foo)
{
return Ok(foo);
}
This doesn't work (parameter foo is null):
MyInputFormatter.cs
public override async Task<InputFormatterResult> ReadRequestBodyAsync(InputFormatterContext context)
{
List<string> input = new List<string>();
using (StreamReader reader = new StreamReader(context.HttpContext.Request.Body))
{
while (!reader.EndOfStream)
{
string line = (await reader.ReadLineAsync()).Trim();
input.Add(line);
}
}
return InputFormatterResult.Success(input.ToArray());
}
MyController.cs
[HttpPost("/foo", Name = "Foo")]
public IActionResult Bar([FromBody] string[] foo)
{
return Ok(string.Join(" ", foo));
}
The difference is that in the controller I'm now accepting an array of strings instead of a string and in the formatter I'm reading the input line by line and in the end returning it as an array.
What am I missing? :/
EDIT: How my formatter actually looks, more or less (if it makes any difference):
public class MyInputFormatter : InputFormatter
{
public MyInputFormatter()
{
this.SupportedMediaTypes.Add(new MediaTypeHeaderValue(MimeType.URI_LIST)); // "text/uri-list"
}
public override bool CanRead(InputFormatterContext context)
{
if (context == null) throw new ArgumentNullException(nameof(context)); // breakpoint here not reached
if (context.HttpContext.Request.ContentType == MimeType.URI_LIST)
return true;
return false;
}
protected override bool CanReadType(Type dataType)
{
return typeof(string[]).IsAssignableFrom(dataType); // breakpoint here not reached
}
public override async Task<InputFormatterResult> ReadRequestBodyAsync(InputFormatterContext context)
{
List<string> input = new List<string>(); // breakpoint here not reached
using (StreamReader reader = new StreamReader(context.HttpContext.Request.Body))
{
while (!reader.EndOfStream)
{
string line = (await reader.ReadLineAsync()).Trim();
if (string.IsNullOrEmpty(line))
{
continue;
}
if (!line.StartsWith("foo-"))
{
return InputFormatterResult.Failure();
}
input.Add(line.Substring("foo-".Length));
}
}
return InputFormatterResult.Success(input.ToArray());
}