【问题标题】:Using Request.Body in custom ModelBinder在自定义 ModelBinder 中使用 Request.Body
【发布时间】:2018-06-26 02:39:56
【问题描述】:

考虑下面的自定义模型绑定器:

[ModelBinder(typeof(CustomModelBinder))]
public class StreamModel
{
    public MemoryStream Stream
    {
        get;
        set;
    }
}

public class CustomModelBinder : IModelBinder
{
    public async Task BindModelAsync(ModelBindingContext bindingContext)
    {
        var request = bindingContext.HttpContext.Request;
        var ms = new MemoryStream();
        request.Body.CopyTo(ms);
        bindingContext.Result = ModelBindingResult.Success(new StreamModel
        {
            Stream = ms
        });
    }
}

ms.Length 的值始终等于 0。 有什么方法可以读取 ModelBinder 中的请求正文吗?

下面的场景对我来说也很奇怪:

public class TestController : Controller
{
    [HttpPost]
    public IActionResult Test(string data)
    {
        var ms = new MemoryStream();
        request.Body.CopyTo(ms);
        return OK(ms.Length);
    }
}

它总是返回0。 但是当删除参数string data时,它会返回实际发布的正文长度。

【问题讨论】:

标签: c# asp.net-core asp.net-core-2.0 asp.net-core-mvc-2.0


【解决方案1】:

问题是您尝试多次读取请求正文。

有关解决方法和更多信息,您应该查看以下问题: Read request body twice

【讨论】:

  • 使用app.Use(next => context => { context.Request.EnableRewind(); return next(context); }); 有效,但我没有多次阅读request.Body。 (我认为 mvc 在内部执行此操作)。 (将在 github 上的 mvc repo 中为此创建一个问题)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-11
  • 2018-01-28
  • 1970-01-01
  • 2013-12-04
  • 1970-01-01
相关资源
最近更新 更多