我正在尝试编写自己的输入格式化程序,它将读取请求正文,按行拆分并将其传递给控制器操作中的字符串数组参数。
这有效(将整个主体作为字符串传递):
启动.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());
}
}
我的控制器.cs
[HttpPost("/foo", Name = "Foo")]
public IActionResult Bar([FromBody] string foo)
{
return Ok(foo);
}
这不起作用(参数 foo 为空):
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());
}
我的控制器.cs
[HttpPost("/foo", Name = "Foo")]
public IActionResult Bar([FromBody] string[] foo)
{
return Ok(string.Join(" ", foo));
}
不同之处在于,在控制器中,我现在接受的是字符串数组而不是字符串,而在格式化程序中,我正在逐行读取输入,最后将其作为数组返回。
我错过了什么?:/
编辑:我的格式化程序实际上看起来如何,或多或少(如果有什么不同的话):
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());
}