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

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何将类型的对象作为参数传递给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

这是Register Route类; (抱歉,我是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吗?

答案

你不能导航到[HttpPost]方法,所以它需要是一个[HttpGet]。要从查询字符串值绑定到复杂对象,您需要使用[FromUri]属性

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

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

以上是关于如何将类型的对象作为参数传递给Web Api Get / Post方法的主要内容,如果未能解决你的问题,请参考以下文章