c# - 如何将类型对象作为参数传递给 Web Api Get/Post 方法
问题描述
这是我的 Post 方法,我正在传递一个包含参数的对象
public class TransactionController : ApiController
{
[HttpPost]
public TransactionResponse mytest2(TransactionOperationInput input)
{
// some operation here
}
}
这是我要测试的 URL
http://localhost:33755/api/Transaction/mytest2?SourceKey=abcdef&Pin=123&Criteria=2018-09-12 00:00:00
结果当方法设置为 POST 和 Get
[HttpPost]:我得到一个错误 405 方法不允许。
[HttpGet] : 输入参数为 NULL
这是注册路由类;(对不起,我是路由表的新手)
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
我需要更新路由表吗?还是我的网址有误?
另外,我应该将服务方法设置为 Post 还是 Get?
解决方案
您无法导航到[HttpPost]
方法,因此它必须是[HttpGet]
. 并且要从查询字符串值绑定到复杂对象,您需要使用[FromUri]
属性
[HttpGet] // can be omitted
public TransactionResponse mytest2([FromUri]TransactionOperationInput input)
有关 web-api 中参数绑定的更多信息,请参阅ASP.NET Web API 中的参数绑定。
推荐阅读
- php - 在查询中进行另一个查询时仅显示一行
- php - AJAX 从第一个和第二个动态下拉列表自动填充下拉列表
- php - 如何将背景图片放在响应式登录表单的 div 上?
- c++ - 如何在 C++ 中将控制台字体设置为 Raster Font 12x8?
- spring-webflux - Spring Web Flux 和 Reactor 中的 Map 与 FlatMap
- python - Python:从标量场的梯度中获取向量场
- amazon-athena - 为什么 Athena JsonSerde 字段名称映射不起作用?
- javascript - 在 500 毫秒内停止点击事件,我该怎么做?
- html - Boostrap 导航栏扩展无法正常工作
- c# - 如何在 C# 中实现 Huffman 代码压缩和解压