【问题标题】:How to pass an object of type as a parameter to Web Api Get/Post method如何将类型对象作为参数传递给 Web Api Get/Post 方法
【发布时间】:2018-09-16 11:20:19
【问题描述】:

这是我的 Post 方法,我正在传递一个包含参数的对象

public class TransactionController : ApiController
{
 [HttpPost]
    public TransactionResponse mytest2(TransactionOperationInput input)
    {
       // some operation here 
    }
}

这是我要测试的网址

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?

【问题讨论】:

  • 您无法导航到 POST 方法(它必须是 [HttpGet])

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


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 2013-12-12
    • 2022-01-22
    • 2018-01-27
    • 2016-06-12
    • 2021-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多