【问题标题】:in Web API 2 how to accept simple types as post parameter along with Route parameter在 Web API 2 中如何接受简单类型作为 post 参数以及 Route 参数
【发布时间】:2013-12-25 04:06:59
【问题描述】:

嗨,经过一番努力,我终于克服了 Angular js 的障碍,将正确的参数传递给我的服务器,但 web api 2 服务无法接受它。

下面是示例代码

[RoutePrefix("api/v2/bids")]
public class BidsController : ApiController
{
    [Route("{quoteId:long}/accept")]
    public HttpResponseMessage AcceptQuote(long quoteId,[FromBody] string remarks)
    {
        HttpResponseMessage response;
            response = Request.CreateResponse(HttpStatusCode.Accepted, quoteId);
        return response;
    }
}

如果你注意到我既有路由参数,也有 sting 类型的 post 参数。当我使用 fiddler 发布以下内容时:

POST http://127.0.0.1:81/api/v2/Bids/101/accept? HTTP/1.1
Authorization: Basic a2lyYW5AYWJjc2hpcHBlci5jb206a2lyYW5AYWJjc2hpcHBlci5jb20=
Accept: application/json, text/plain, */*
Content-Type: application/json;charset=utf-8
Referer: http://127.0.0.1:81/shipper/
Accept-Language: en-US
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0; EIE10;ENUSWOL)
Host: 127.0.0.1:81
Content-Length: 40
DNT: 1
Connection: Keep-Alive
Pragma: no-cache


{"remarks":"Accepting this as the best"}

或者使用angularjs函数:

    function acceptQuote(quoteId, accept_remarks, fnSuccess, fnError) {

        return $resource("/api/v2/Bids/:id/accept", { quoteId: "@id"},
            { "AcceptQuote": { method: "POST", isArray: false } })
            .AcceptQuote({ id: quoteId }, { remarks: accept_remarks }, fnSuccess, fnError);
    }

返回以下错误:

{"Message":"The request is invalid.","ModelState":{"remarks":["Error reading string. Unexpected token: StartObject. Path '', line 1, position 1."]}}

我希望使用 [FromBody] 足以将简单类型作为 post 参数传递,以及我在这里缺少的任何想法。

【问题讨论】:

    标签: angularjs asp.net-web-api


    【解决方案1】:

    [FromBody] 的工作方式略有不同。请检查此Parameter Binding in ASP.NET Web API。如果你想得到字符串[FromBody] string remarks,那么你的身体必须是这样的:

    "Accepting this as the best" 
    

    不是 JSON。另一方面,如果正文包含 JSON,使用 ASP.NET Web API 使用它的最自然方式是通过实体/对象。所以,我们可以创建这个

    public class MyObject
    {
       public string remarks { get; set; }
    }
    

    控制器动作应该是这样的:

    [Route("{quoteId:long}/accept")]
    public HttpResponseMessage AcceptQuote(long quoteId, MyObject myObject)
    {
        var remarks = myObject.remarks;
    

    【讨论】:

    • 再次感谢,您提供的链接对于了解后台发生的事情非常有帮助。
    猜你喜欢
    • 1970-01-01
    • 2012-09-04
    • 2017-09-28
    • 2017-11-25
    • 1970-01-01
    • 2018-05-29
    • 2017-03-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多