【问题标题】:web api from body value is null?来自正文值的 web api 为空?
【发布时间】:2014-11-06 21:25:49
【问题描述】:

我在这里检查了与此类似的问题:

web-api POST body object always null

这与我的场景中发生的情况不完全匹配。我正在使用以下请求标头内容类型向我的 api 发出请求:

Key Value
Content-Type    application/x-www-form-urlencoded

然后我的请求正文是我从另一个服务获得的响应,我无法更改

Response=SomeLongStringOfBAse64EncodedData

我可以看到通过在其上设置断点来命中的我的 Api Post Method 如下:

public HttpResponseMessage Authenticate([FromBody]string Response) 

然而响应字符串总是得到空值,即使我在请求正文中看到它我无法理解。

【问题讨论】:

  • 你怎么打电话给Authenticate
  • 一个页面被加载到我的网站 - 它有一个隐藏的表单,上面有一个 POST 操作。对它的操作是我的 Authenticate URL 路由,表单还包含 Response Base 64 字符串。我认为当我到达断点时请求正在生成 - 只是无法弄清楚为什么请求正文没有绑定到我的参数
  • @TheRiddler 请发布Authenticate 的调用方式以及操作路线。

标签: c# asp.net asp.net-web-api asp.net-web-api2


【解决方案1】:

对于这样的动作方法

public HttpResponseMessage Authenticate([FromBody]string Response),

您需要有这样的请求正文,才能进行绑定。

=SomeLongStringOfBAse64EncodedData

如果你想绑定Response=SomeLongStringOfBAse64EncodedData,你需要像这样改变action方法。

public HttpResponseMessage Authenticate(SomeClass response)

并添加一个类

public class SomeClass
{
    public string Response { get; set; }
}

【讨论】:

  • FromBody 可能很棘手,如果您使用 RestKit,我在 iOS 中发现了一些问题 - 我必须将其作为 json 发布,其中单个属性为空引号。 ''='价值'。在 Android 中,如果你使用 Retrofit - 那么只要你用@Body 发布它,webapi 就会把它捡起来。
  • 如果使用 JSON.stringify(item); 则不需要在其前面加上 '=' 符号;
猜你喜欢
  • 1970-01-01
  • 2014-05-09
  • 2019-05-27
  • 2021-01-14
  • 2021-12-06
  • 2020-06-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多