如何将类型的对象作为参数传递给Web Api Get / Post方法

时间:2018-09-16 11:20:19

标签: c# asp.net-mvc api asp.net-web-api routes

这是我的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并获取

[HttpPost]:我收到错误405方法,这是不允许的。

[HttpGet]:输入参数为NULL

这是注册路由类; (对不起,我是Route表的新手)

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?

1 个答案:

答案 0 :(得分:0)

您无法导航到[HttpPost]方法,因此它必须是[HttpGet]。要从查询字符串值绑定到复杂对象,您需要使用[FromUri]属性

[HttpGet] // can be omitted 
public TransactionResponse mytest2([FromUri]TransactionOperationInput input)

有关web-api中参数绑定的更多信息,请参见Parameter Binding in ASP.NET Web API