简体   繁体   中英

POST parameter to web api being set as null

I'm trying to use ng-resource to POST a value to my web-api and get the value back in javascript.

While the request seems to go through alright, the parameter being passed to my function public string AddOrder([FromBody]string order) seems to be set as 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.
}

raw request

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

raw reply

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

Anybody have any ideas?

Edit

The quickest / easiest solution to this was to wrap the string in an object as follows:

Order.cs

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

ProductController.cs

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

尽管我不确定是什么导致该字符串在控制器中为空,但您可以发送一个包装字符串的对象,而不是将其发布到Web API控制器,而该对象将被正确接受。

To post to a string to the web api it needs to be preceded by = .Also there is no Content-Type set on the request.

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

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

The above should work

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM