Ori Refael
Ori Refael

Reputation: 3008

c# web api post request null

Using c# web api server.

my client call looks like:

$.ajax({
    type: method,
    url: urls.server + url,
    data: (method === "POST" ? '='+JSON.stringify(data) : data),
    dataType: "json",
    success: function(data){
        callback(data);
    },
    error: function(err) {
        onError(err);
    }
});

My C# server method looks like:

[HttpPost, Route("All/GetMyTeam")]
public POST_GetMyTeam_Response Post(GetMyTeam_Request request)
{
    return new POST_GetMyTeam_Response();
}

Now, whenver i use the 'Advanced Rest Client' which is a Google's Chrome plugin I get my request perfectly fine. But, If I send this same request (I see in the network's area in chrome's debug window), the payloads are the same, the request arrives but all fields inside are null.

public class GetMyTeam_Request
{
    public string UserId;
    public string TeamId;
}

I also tried removing the '=' from the json client but I noticed most answer are leading to this addition (though they never told it suppose to be wrapped with apostrophe, but otherwise it's not working ). Tried to add contentType-application/json in both headers or as-is field in the ajax request..

TIA.

Upvotes: 3

Views: 539

Answers (1)

Habib
Habib

Reputation: 223187

In your ajax request specify

contentType: 'application/json'

and also you don't need "=" string appended before json string data

data: (method === "POST" ? '='+JSON.stringify(data) : data),
                         //^^^^ here

Remove the = sign and it should work.

$.ajax({
    type: method,
    url: urls.server + url,
    data: (method === "POST" ? JSON.stringify(data) : data),
    dataType: "json",
    contentType: 'application/json',
    success: function(data){
        callback(data);
    },
    error: function(err) {
        onError(err);
    }
});

Upvotes: 2

Related Questions