IModelBinder:访问请求的原始数据

时间:2015-05-13 11:57:03

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

我试图通过IModelBinder界面查看POST中发送的文本。我有类似的东西:

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

......哪里???应该是在POST中发送的文本。它应该是一个文本块(我想),但我不知道如何访问它。有人可以开导我吗?

1 个答案:

答案 0 :(得分:1)

好的,根据@ ScottRickman的建议,我查看了http://linux-mm.org/Drop_Caches上的文章,并看到了如何将其应用于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;
    }
}

这完全符合要求。