当前位置: 动力学知识库 > 问答 > 编程问答 >

c# - Can't pass serialized Json to Web API action

问题描述:

NOTE Please see the update at the bottom.

I'm picking up maintenance on an existing (working) application.

The application receives data into a class via a post to a Web API controller action.

However when I try to test this by posting it some data it just gives an empty object.

I assumed that my Json must be wrong so I tried sending the Json string as text and deserializing manually, and this works fine, returning the populated object I would expect to see.

I've searched online and seen various suggestions about adding attributes to the parameters but this doesn't do it for me.

The code looks pretty much as follows:

 [HttpPost]

[AllowBasicAuthentication]

public async Task<MyResponse> ProcessData(

[FromUri]string key,

[FromUri]string name,

[FromUri]string value1,

[FromBody] DataClass value // this is never populated

)

{

// the following returns the data as expected

var test = new JavaScriptSerializer().Deserialize<DataClass>(value1);

...

}

The jQuery I'm using to test this is as follows:

$('#post').click(function () {

var key = $('#key').val();

var name = $('#name').val();

var value1 = $('#value').text();

var value = JSON.parse(value1);

var url = '/api/ProcessData/?key=' + key

+ '&name=' + name

+ '&value1=' + value1

/* with this post value appears in action as an instantiated but empty object */

$.post(url, { value: value })

.success(function (r) {

...

})

.fail(function (r) {

...

})

/* also tried the following, but value appears as null object

$.ajax({

url: url,

type: 'POST',

cache: false,

contentType: "application/json",

data: value,

success: function (r) {

alert(r);

}

});

*/

});

[EDIT]

Just to clarify, I added the value1 string parameter to test that the Json can be deserialized correctly, which it can, so the Json is ok and the class is ok.

UPDATE

This works when called from Postman so the error must be in the jQuery.

Can anyone show the correct way to do this?

Thanks

[/EDIT]

分享给朋友:
您可能感兴趣的文章:
随机阅读: