c# - IModelBinder : access the raw data of the request

标签 c# asp.net-mvc asp.net-mvc-5 model-binding

我正在尝试查看通过 IModelBinder 接口(interface)在 POST 中发送的文本。我有类似的东西:

    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        if (controllerContext.HttpContext.Request.ContentType.ToLowerInvariant().StartsWith("my special content type"))
        {
            var data = ???

...在哪里???应该是在 POST 中发送的文本。它应该是一堆文本(我认为),但我不知道如何访问它。谁能赐教一下?

最佳答案

好的,根据@ScottRickman 的建议,我查看了 Accessing the raw http request in MVC4 上的文章并了解如何将其应用于 IModelBinder:

public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
    if (controllerContext.HttpContext.Request.ContentType.ToLowerInvariant().StartsWith("my special content type"))
    {
        var body = GetBody(controllerContext.HttpContext.Request);
        var model = MyCustomConverter.Deserialize(body, bindingContext.ModelType);
        return model;
    }
}

private static string GetBody(HttpRequestBase request)
{
    var inputStream = request.InputStream;
    inputStream.Position = 0;

    using (var reader = new StreamReader(inputStream))
    {
        var body = reader.ReadToEnd();
        return body;
    }
}

这完全符合预期。

关于c# - IModelBinder : access the raw data of the request,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30214109/

相关文章:

c# - 后台 worker 订阅事件

c# - 在字段具有值之前拒绝使用方法

c# - 在 asp.net core/kestrel 中记录异常

asp.net-mvc - 基于 View 模型属性的网格排序

c#多级指针,内存读取

asp.net - 使用 NInject 连接依赖项的选项

asp.net-mvc - asp.net mvc如何正确测试 Controller

c# - MVC5 DataContext 最佳实践?

asp.net-mvc - MVC5 - 用于特定操作的 block Controller 输出缓存

c# - 覆盖登录页面上的防伪 token 错误