【问题标题】:Routing POST with Query Parameters in MVC Web API在 MVC Web API 中使用查询参数路由 POST
【发布时间】:2013-05-14 21:14:36
【问题描述】:

在一个 Web Apì 项目中,我想使用类似的东西:

POST/mycontroller/1

还有 POST/mycontroller/1?user=john

使用 GET 很容易,因为框架可以正确地路由到每个函数。但是,当我使用 POST 时,它不起作用。我在同一个控制器中有 2 个 POST 函数。例如:

void Post(int id, string content)

void Post(int id, string content, string user)

我希望当我调用 POST/mycontroller/1?user=john 时,框架会路由到 Post(int id, string content, string user)

我知道我可以使用绑定模型,做一个模型类和一个独特的 POST 函数,但它是一团糟,因为我有很多函数,我希望能够使用查询参数来路由正确的函数。 有可能吗?

【问题讨论】:

    标签: c# asp.net-mvc


    【解决方案1】:

    尝试使用 [FromBody] 和 [FromUri] 属性声明参数,如下所示:

        public string Post(int id, [FromBody]string content, [FromUri] string user)
        {
            return "content = " + content + "user = " + user;
        }
    

    使用上面的代码我可以调用

    /Test/1?user=Ryan

    请求正文

    “测试体”

    结果是:

    “内容 = 测试 Bodyuser = Ryan”

    希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-11-07
      • 2018-04-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-07
      • 1970-01-01
      • 2019-11-21
      相关资源
      最近更新 更多