gpt4 book ai didi

c# - 通过输入格式化程序将主体 POST 到参数

转载 作者:太空宇宙 更新时间:2023-11-03 14:40:08 25 4
gpt4 key购买 nike

我正在尝试编写自己的输入格式化程序,它将读取请求正文,按行拆分并将其传递到 Controller 操作中的字符串数组参数中。


这有效(将整个主体作为字符串传递):

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);
}

这不起作用(参数 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());
}

MyController.cs

[HttpPost("/foo", Name = "Foo")]
public IActionResult Bar([FromBody] string[] foo)
{
return Ok(string.Join(" ", foo));
}

不同之处在于,在 Controller 中,我现在接受一个字符串数组而不是一个字符串,而在格式化程序中,我逐行读取输入,最后将其作为数组返回。


我错过了什么? :/


编辑:我的格式化程序的实际外观,或多或少(如果有什么不同的话):

    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());
}

最佳答案

我已经在请求处理程序方法中使用您的代码创建了一个测试输入格式化程序,它工作正常,这就是它的样子:

public class TestInputFormatter : IInputFormatter
{
public bool CanRead(InputFormatterContext context) => true;

public async Task<InputFormatterResult> ReadAsync(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());
}
}

我只看到您的代码中有一点可能是错误的——您的输入格式化程序的注册。文档说:Formatters are evaluated in the order you insert them. The first one takes precedence.尝试这样注册:

options.InputFormatters.Insert(0, new TestInputFormatter());

它在我的测试项目中使用了完全这样的注册。因为当你调用 options.InputFormatters.Add它将被添加到输入格式化程序集合的末尾,并且您的请求可能会由位于该集合中第一个的其他输入格式化程序处理。

关于c# - 通过输入格式化程序将主体 POST 到参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57361233/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com