Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 292
Ori Refael Avatar asked Jun 11 '26 18:06

Ori Refael


1 Answers

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);
    }
});
like image 139
Habib Avatar answered Jun 14 '26 06:06

Habib



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!