terbubbs
terbubbs

Reputation: 1512

PostAsJsonAsync returning null

I am currently posting a json string to an API to receive an object containing various values.

This is the json string i am posting:

{"SomeProperty":1,"DimensionOne":4,"DimensionTwo":6,"IdNumber":0}

Now I don't have issues with the Json string itself because I've tested this string in Fiddler going to the api, and it works perfectly fine, returning all the values I need.

The only difference between what I am doing and what Fiddler is doing is that I am going from the script to a WebService that posts to the API.

Here is the code I am using for the WebService:

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
[ScriptService]
public class WebService1 : System.Web.Services.WebService
{
    [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public ObjectType Relay(string json)
    {
        const string url = "https://api.com";
        var client = new HttpClient {BaseAddress = new Uri(url)};

        client.DefaultRequestHeaders.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

        var response = client.PostAsJsonAsync("api/v1/GetObject", json).Result;

        if (response.IsSuccessStatusCode)
        {
            var objectRequest = Task.FromResult(response.Content.ReadAsStringAsync());
            return JsonConvert.DeserializeObject<ObjectType>(objectRequest.Result.Result);
        }

        return null;
    }
}

So far it has only returned null (obviously because response.IsSuccessStatusCode is not TRUE)

But when I comment out the if brackets and remove the return null, it gives me an empty object when I should be receiving data. All the inputs are correct.

I'm wondering if I should be using a method other than PostAsJsonAsync, or if there is anything else I should be doing to the json string or json header.

Again, the json string is in correct format as it worked with Fiddler and has previously worked when going directly from the website to the API (without a WebService).

I'd appreciate any suggestions. Thanks in advance.

Upvotes: 2

Views: 1650

Answers (1)

Khanh TO
Khanh TO

Reputation: 48982

You're sending a https request. Although client certificate is optional in the protocol, but you need a certificate for your HttpClient in case the server requires it: Make Https call using HttpClient

Upvotes: 1

Related Questions