【发布时间】:2018-04-24 14:23:04
【问题描述】:
我正在尝试一个支持 GET 和 POST 的 webapi,但 POST 方法需要传递一个字母数字参数,但 GET 应该忽略任何参数。
[HttpPost]
[HttpGet]
[Route("payment")]
public virtual async Task<HttpResponseMessage> PaymentBase([FromBody] string hostOtp)
{
return await ((IApiPaymentController)this).Payment(hostOtp);
}
我试过了,
-
PaymentBase([FromBody] string hostOtp)和 PaymentBase([FromBody] string hostOtp="")PaymentBase(string hostOtp="")
使用这种方法PaymentBase(string hostOtp="") GET 可以正常工作,但使用 POST hostOtp 永远不会被绑定。
这是邮递员代码,
var settings = {
"async": true,
"crossDomain": true,
"url": "http://localhost:5094/api/payment/Payment",
"method": "POST",
"headers": {
"securitytoken": "0WnIxDep1knex1P13FmTWFKmIOBhgyc",
"content-type": "application/x-www-form-urlencoded",
"cache-control": "no-cache",
"postman-token": "123d6825-c723-732d-737c-1964dd8f271f"
},
"data": {
"hostOtp": "eqweef"
}
}
$.ajax(settings).done(function (response) {
console.log(response);
});
当[FromBody] string hostOtp 出现错误时从邮递员那里开火,
"没有 MediaTypeFormatter 可用于读取 'String' 类型的对象 来自媒体类型为“application/octet-stream”的内容。”
【问题讨论】:
-
为什么不为 HttpGet 和 HttpPost 提供两个单独的方法?
-
如果您需要此
PaymentBase(string hostOtp="")来使用 POST 方法,那么您需要在此处查看我的答案 => stackoverflow.com/a/35389449/797882 -
@FelixToo GET 已经在生产中用于移动应用,无法触及,新需求也需要传递此参数
-
请在投票时让我知道我是否走错了方向?
标签: c# post asp.net-web-api get optional-parameters