[英]Using FromUri OR FromBody in MVC 5
I would like to expose my POST method in a way that allows users call it with parameters either encoded in the url or written inside the request body. 我想公开我的POST方法,该方法允许用户使用在url中编码或写在请求正文中的参数来调用它。 Pseudocode:
伪代码:
public HttpResponseMessage MyMethod([FromUri, FromBody] parameters)
{
//..
}
It isn't even possible via exposing two methods: 通过公开两种方法甚至是不可能的:
public HttpResponseMessage MyMethod([FromUri] parameters)
public HttpResponseMessage MyMethod([FromBody] parameters)
Because they have the same signature. 因为它们具有相同的签名。 How to achieve this in a simple way?
如何以简单的方式实现这一目标?
You can't do it out of the box; 您不能开箱即用。 if you try to use both the attributes together you will get this fine error: Can't bind parameter 'xxx' because it has conflicting attributes on it.
如果您尝试同时使用这两个属性,则会出现以下错误: 无法绑定参数“ xxx”,因为它具有冲突的属性。
Two possible solution: 两种可能的解决方案:
[FromUri]
and use a custom action filter (like this ) to check for body content and, if present, manually parse it and bind it to the correct method parameters - less easy way, but more powerful. [FromUri]
并使用自定义操作过滤器(像这样 )来检查身体的内容和,如果存在的话,手动解析它,并将其绑定到正确的方法参数-不容易的方式,但功能更强大。 Hope it helps :) 希望能帮助到你 :)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.