将web api的POST参数设置为null

时间:2015-01-12 10:50:12

标签: javascript c# asp.net asp.net-web-api ngresource

我正在尝试使用ng-resource将值发布到我的web-api并在javascript中返回值。

虽然请求似乎没有问题,但传递给我的函数public string AddOrder([FromBody]string order)的参数似乎设置为null

orderController.js

var result = $scope.store.sendOrder("hello");

store.js

function store($resource) {

    var Resource = $resource('/api/products/');
    this.products = Resource.query();

    this.sendOrder = function (order) {

        var sendOrder = $resource('/api/products');

        var result = sendOrder.save("Helloa"); <---

        return result;
    }
}

ProductController.cs

[Route("api/products")]
[HttpPost]
public string AddOrder([FromBody]string order)
{
    return order; //When I put a breakpoint here and check the value of order, it is null.
}

原始请求

POST http://localhost:12345/api/products HTTP/1.1
Host: localhost:12345
Connection: keep-alive
Content-Length: 6
Accept: application/json, text/plain, */*
Origin: http://localhost:12345
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36
Content-Type: application/json;charset=UTF-8
Referer: http://localhost:12345/Home/Cart
Accept-Encoding: gzip, deflate
Accept-Language: en-GB,en;q=0.8,es;q=0.6,en-US;q=0.4
Cookie: ai_user=fc592beca77b4a5e8c4a95db221a574a|2014-12-04T18:36:22.7128874+00:00

hello

原始回复

HTTP/1.1 200 OK
Cache-Control: no-cache
Pragma: no-cache
Content-Type: application/json; charset=utf-8
Expires: -1
Server: Microsoft-IIS/8.0
X-AspNet-Version: 4.0.30319
X-SourceFiles: =?UTF-8?B?QzpcVXNlcnNcbXJ5YW4uQVNBVklFXERvY3VtZW50c1xleHByZXNzb1xFeHByZXNzb1x3ZWJzaXRlc1xjb25zdW1lclxhcGlccHJvZHVjdHM=?=
X-Powered-By: ASP.NET
Date: Mon, 12 Jan 2015 10:45:03 GMT
Content-Length: 4

null

有人有什么想法吗?

修改

对此最快/最简单的解决方案是将字符串包装在对象中,如下所示:

Order.cs

public class Order
{
    public string order { get; set; }
}

ProductController.cs

[Route("api/products")]
[HttpPost]
public Order AddOrder([FromBody]Order order)
{
    return order;
}

2 个答案:

答案 0 :(得分:1)

虽然我不确定是什么原因导致字符串在控制器中为空,而不是将字符串发布到Web API控制器,您可以发送一个包裹字符串的对象,这将被正确接受。

答案 1 :(得分:0)

要将字符串发布到网络API,需要先加=。此外,请求中没有设置Content-Type

  var sendOrder = $resource('/api/products',{}, { query: {method:'POST', headers: {'Content-Type': 'application/json'});

  var result = sendOrder.save("=" + "Helloa");

以上应该有效