首页 > 解决方案 > 如何将类型对象作为参数传递给 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?

标签: c#asp.net-mvcapiasp.net-web-apiroutes

解决方案


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

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

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


推荐阅读