c# - 通过输入格式化程序将正文发布到参数
问题描述
我正在尝试编写自己的输入格式化程序,它将读取请求正文,按行拆分并将其传递给控制器操作中的字符串数组参数。
这有效(将整个主体作为字符串传递):
启动.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());
}
解决方案
我弄清楚到底是什么问题。我有一个自定义的 ModelBinder 进行干扰,捕获任何不是字符串的内容和自定义接口的实现(用于其他发布数据)。这就是为什么它适用于字符串和其他输入有效负载(接口的实现),但不适用于字符串数组。该绑定器应该用于查询参数(以便能够处理自定义类型),但最终也触发了这个 POST 有效负载。
推荐阅读
- reactjs - 在 Meteorjs 中显示最新创建的用户和角色时的 Pub-Sub 问题
- mysql - 想要更新数据库中输入的条目。我有代码并显示错误:
- r - R在打开netcdf文件时崩溃
- rest-assured - 放心:- 从使用 Pathparam 和 FormParam 创建的 Post 请求中获得 404 响应
- json - 使用nodejs获取带有标头的json
- javascript - 散点图缩放在 d3.js 中无法正常工作
- html - 如何将父 div 的高度设置为具有位置的子 div:绝对
- python - 如何随意停止和启动线程
- javascript - 为什么这不是一个完美的正方形?
- javascript - 我在 ng-repeat 中使用了一个函数,但它的重复次数比数组的总长度多很多倍