【问题标题】:Call WEB API method with Simple Type parameters Method from Winform APPWinform APP中使用简单类型参数方法调用WEB API方法
【发布时间】:2016-01-20 17:36:09
【问题描述】:

我对 Web API 还很陌生,所以请原谅一个愚蠢的问题

我有一个 Web API 2 方法......

[System.Web.Http.HttpPost]
public MyAPIController AddItemToBasket(Guid b, Guid l, Guid a, 
                                       Guid cid, int d, int p, int q)
{
    ..blah blah
}

我正在整理一个 Winform 测试应用程序。

我似乎无法将参数传递给方法。 我看到许多示例,其中 POST 方法将对象作为参数,这看起来很简单,但奇怪的是,传入简单类型似乎更让人头疼。

看来我需要填充一个 HTTPContent 变量并传递它,但我不知道该怎么做。

或者,我应该将这些参数包装在一个对象中。无论哪种方式 - 我想知道如何做到这一点以备将来使用。

TIA,

蚂蚁

【问题讨论】:

    标签: asp.net-web-api httpcontent simpletype


    【解决方案1】:

    默认情况下,对于POST 操作,Web Api 框架将从请求的消息正文中查找参数。如果您尝试从查询字符串中传递参数,则需要使用 [FromUri] 属性。

    [HttpPost]
    public IHttpActionResult AddItemToBasket([FromUri]Guid b, [FromUri]Guid l, [FromUri]Guid a, 
                                           [FromUri]Guid cid, [FromUri]int d, [FromUri]int p, 
                                           [FromUri]int q)
    {
        ..blah blah
    }
    

    或者更好地创建一个NewItem Object 并只用属性标记一次。

    public class NewItem
    {
         public Guid b { get; set; }
         public Guid l { get; set; }
         public Guid a { get; set; }         
         public Guid cid { get; set; }       
         public int d { get; set; }       
         public int p { get; set; }       
         public int q { get; set; }
    }
    
    [HttpPost]
    public IHttpActionResult AddItemToBasket([FromUri]NewItem item)
    {
        ..blah blah
    }
    

    但是,我强烈建议您顺其自然,按照预期的方式使用 POST api 操作。也就是将新的项目数据发布到消息正文中。

    【讨论】:

    • 谢谢.....我倾向于“请求参数”对象,所以会这样。再次感谢您的信息
    猜你喜欢
    • 1970-01-01
    • 2019-06-11
    • 2013-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-11
    • 2019-07-21
    • 1970-01-01
    相关资源
    最近更新 更多