0
votes

I send a request to an API I get null but when I execute the same API in swagger I get the result back.

Below is my ASP.NET code:

HttpClient client = new HttpClient();

var data = new
            {
                test = "mydata"
            };

client.BaseAddress = new Uri("weburl.com");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

using (client)
{
    HttpResponseMessage res = await client.PostAsJsonAsync("api/test", data);

    if (res.ReasonPhrase == "OK")
    {
        res.EnsureSuccessStatusCode();

        if (res.IsSuccessStatusCode)
        {
            var resualt = res.Content;
            var res2 = await resualt.ReadAsStringAsync();
            var json = JsonConvert.DeserializeObject<JsonModelApi>(res2);

            if (json.Succeed)
            {
                return json.Result;
            }
            else 
                return null;
        }
        else 
            return null;
    }
    else 
        return null;
}

HttpResponseMessage res = await client.PostAsJsonAsync("api/test", data);

res output :

{StatusCode: 200, ReasonPhrase: 'OK', Version: 1.1, Content: System.Net.Http.StreamContent, Headers: { Vary: Accept-Encoding Protect: SA Date: Sun, 02 Sep 2018 11:20:16 GMT Set-Cookie: __cfduid=dd54b1f82b2eb402e21bae199246157631535887216; expires=Mon, 02-Sep-19 11:20:16 GMT; path=/; domain=.myweb; HttpOnly X-Powered-By: Huricane 11 X-Powered-By: ASP.NET Server: cloudflare CF-RAY: 453f961cb483bead-FRA Connection: keep-alive Content-Length: 0 }}

Can anybody help me?

Thank you.

2
why is Content-Length: 0 ? - Ahmad Ghasemi
Can you show us the result you get when calling from Swagger? - Vinyl Warmth
this is entered in swagger: { "test": "mydata" } - Ahmad Ghasemi
response body in swagger: { "Succeed": true, "Result": "a89d94be-1ed5-43df-ad6f-d90c8cac6c1c" } - Ahmad Ghasemi
Answers do not go in the question and I have rolled back your changes. If you want to add an answer, then add an answer - user3559349

2 Answers

0
votes

I solved the problem with this code :

            client.BaseAddress = new Uri("mywebapi");
            client.DefaultRequestHeaders.UserAgent.ParseAdd("Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:61.0) Gecko/20100101 Firefox/61.0");
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

with added user-agent to HttpClient, I could result in content:

            client.DefaultRequestHeaders.UserAgent.ParseAdd("Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:61.0) Gecko/20100101 Firefox/61.0");
-1
votes

Try This May Be its work :

var data = await MobileService.Client.InvokeApiAsync<RETURN TYPE, SEND_TYPE>($"api/test", 
HttpMethod_TYPE, null);