嗨,经过一番努力,我终于通过角度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]
足以将简单类型作为帖子参数传递,任何想法都归结为我在这里缺少的其他内容。
答案 0 :(得分:3)
[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; }
}
Controller操作应该如下所示:
[Route("{quoteId:long}/accept")]
public HttpResponseMessage AcceptQuote(long quoteId, MyObject myObject)
{
var remarks = myObject.remarks;