C# HttpClient PostAsync not returning the response body even if sysparam_fields are passed where as postman tool is returning the response body

Murali D
Kilo Contributor

Hi,

I am developing a C#.NET application which interacts with service now via table API.

I am facing an issue with POST request to service now table api. I have been passing the sysparm_fields in the base url of post request, data inserted without any issues but response body not exists with specified sysparm_fields.

I have tried with postman tool to verify the same and I am getting getting response body.

Below is the method I am using.

using System.Net.Http;
using System.Net.Http.Headers;
using Newtonsoft.Json;

private void insertAsset()
{
    StringContent requestContent = null;
    SNOWAssetForSave ObjTempAsset = null;
    StringBuilder sbInsertAPIResponse = null;

    string URL = txtSnowTableAPIUrl.Text.Trim();
    URL = "https://<devinstancename>.service-now.com/api/now/table/alm_asset";
    string urlParameters = "?sysparm_fields=sys_id,asset_tag,display_name";

    URL = string.Concat(URL, urlParameters);

    ObjTempAsset = new SNOWAssetForSave();
    ObjTempAsset.u_asset_type = "Hardware";            
    ObjTempAsset.model_category = "81feb9c137101000deeabfc8bcbe5dc4";
    ObjTempAsset.model = "26431e62ac10a501177f7cd98f0de15e";
    ObjTempAsset.asset_tag = "test asset tag From API client-1";
    ObjTempAsset.serial_number = "1234567890";
    ObjTempAsset.assigned_to = "62826bf03710200044e0bfc8bcbe5df1";

    if (ObjTempAsset != null)
    {
        var modifiedAssetJSON = JsonConvert.SerializeObject(ObjTempAsset);
        requestContent = new StringContent(modifiedAssetJSON, Encoding.UTF8, "application/json");
    }

    var httpHandler = new HttpClientHandler
    {
        Credentials = new System.Net.NetworkCredential("username", "password")
    };

    using (var httpClient = new HttpClient(httpHandler))
    {
        httpClient.BaseAddress = new Uri(URL);
        httpClient.DefaultRequestHeaders.Accept.Clear();
        httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

        HttpResponseMessage response = httpClient.PostAsync(URL, requestContent).Result;
        response.EnsureSuccessStatusCode();

        if (response.IsSuccessStatusCode)
        {
            HttpContent content = response.Content;
            string jsonContent = content.ReadAsStringAsync().Result;
        }
        else
        {
            Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);
        }
    }
}

In the above method I can get IsSuccessStatusCode as true, response code as 201/created but response.Content (statements highlighted in yellow) returns null and cannot read from the content to use the recently used object details for further processing.

I need the new object details to add a reference to some other object.

I have tried with both HttpClient and HttpRequest but no luck.

Can somebody suggest what I am missing in the above code to get the response body or there an alternate or better way to achieve this?

 

Thanks in advance.

Regard,

Murali.

 

4 REPLIES 4

Tony Chatfield1
Kilo Patron

Hi, what debugging have you undertaken?
Have you tried logging\printing your response payload as a string to confirm it is correct\as expected?

I have no experience with .net libraries\functionality but would check that 'Result' was an upper case R,
string jsonContent = content.ReadAsStringAsync().Result;

as if this is mapped directly to the payload content then it is possibly 'r' IE 'result'

Hi Tony,

Thanks for your response.

I have logged the Result to console and below is the response object content.

{StatusCode: 201, ReasonPhrase: 'Created', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
Set-Cookie: glide_user=; Max-Age=0; Expires=Thu, 01-Jan-1970 00:00:10 GMT; Path=/; HttpOnly;Secure
Set-Cookie: glide_user_session=; Max-Age=0; Expires=Thu, 01-Jan-1970 00:00:10 GMT; Path=/; HttpOnly;Secure
Set-Cookie: glide_user_route=glide.da56651f7eba464da734a6ac74ae1d60; Max-Age=2147483647; Expires=Wed, 01-Mar-2090 14:18:47 GMT; Path=/; HttpOnly;Secure
Set-Cookie: glide_session_store=8F4521E207210110E164F1D08C1ED0CF; Max-Age=300; Expires=Fri, 11-Feb-2022 11:09:40 GMT; Path=/; HttpOnly;Secure
X-Is-Logged-In: true
X-Transaction-ID: ab456de20721
Location: https://service-now.com/api/now/table/alm_asset/NULL
Transfer-Encoding: chunked
Date: Fri, 11 Feb 2022 11:04:40 GMT
Server: ServiceNow
Strict-Transport-Security: max-age=63072000; includeSubDomains
}}

Regarding the question related to below statement

string jsonContent = content.ReadAsStringAsync().Result;

It should be "Result" to get the response content when not using await in C#. If I use result I cannot compile due to compile time error.

 

Thanks,

Murali.

Hi, looking at the payload you have printed/logged, the SNC server response (that you saw in postman) is absent (as you already stated), unfortunately I cannot assist with this as outside of my experience. If no-one else from the SNC community is able to assist then this might be something you would need to raise with a C# .NET community.

Hi Tony,

 

Thanks for your response and time.


I have figured out the root cause of the issue.


While posting the payload for data insert, it should never contain sys_id field with any value. If sys_id is there, data was inserted but, no JSON response is received.

After I have excluded the sys_id, it is all good.

Thanks,

Murali.