2012-05-24 47 views
0

我不得不asp.net MVC 3 - 在paramterized控制器方法读取POST负载

[HttpPost]   
public ActionResult Foo() 
{ 
    // read HTTP payload 
    var reqMemStream = new MemoryStream(HttpContext.Request.BinaryRead(HttpContext.Request.ContentLength)); 
.... 
} 

有效载荷是应用/ JSON;工作得很好;然后我改为

public ActionResult Foo(string thing) 
{ 
.... 
} 

的意图是张贴到MyController/Foo?thing=yo 现在我不能读取有效载荷(长度为正确的,但该流为空)。我的猜测是,控制器管道已经吃掉了有效载荷,寻找可以映射到方法参数的表单发布数据。有没有什么方法可以阻止这种行为(当然,MVC不应该吃掉其类型标记为JSON的有效载荷,它只应该查看表单发布数据)。我的解决办法是“东西”添加到JSON,但我真的不喜欢那个

回答

3

尝试阅读之前复位输入流中的位置:

public ActionResult Foo(string thing) 
{ 
    Request.InputStream.Position = 0; 
    var reqMemStream = new MemoryStream(HttpContext.Request.BinaryRead(HttpContext.Request.ContentLength)); 
    .... 
} 

现在,这就是说,如果您正在发送application/json有效载荷为什么神圣地球上难为的简单定义和使用视图模型直接读取请求流来代替:

public class MyViewModel 
{ 
    public string Thing { get; set; } 
    public string Foo { get; set; } 
    public string Bar { get; set; } 
    ... 
} 

然后:

public ActionResult Foo(MyViewModel model) 
{ 
    // use the model here 
    .... 
} 

ASP.NET MVC 3有一个内置的JsonValueProviderFactory它允许您自动绑定JSON请求到模型。如果你使用的是旧版本,那么像Phil Haack在his blog post中说明的那样添加这样的工厂非常容易。

+2

ty关于你的“为什么在地球上,...”,在我的情况下,没有意见或模型。我的电话都是纯粹的AJAX呼叫。我只是将MVC的C部分用作'REST'服务器端的一个很好的框架。微软的json支持对于复杂类型并不好,我使用json.net代替 – pm100

+1

Request.InputStream.Position = 0;是一个有效的答案。 –