Click here to Skip to main content
15,886,032 members
Please Sign up or sign in to vote.
1.00/5 (3 votes)
See more:
I'm posting to web API, but it keeps loading the page without any response...

What I have tried:

First I tried this code after putting my url, email, key and service:

public async Task<string> Login()
       {
           using (var client = new HttpClient())
           {
               client.BaseAddress = new Uri("my url");
               var content = new FormUrlEncodedContent(new[]
               {
                   new KeyValuePair<string,string>("email","my email"),
                   new KeyValuePair<string,string>("api_key","my key"),

               });
               HttpResponseMessage rm = await client.PostAsync("my service", content);
               if(rm.IsSuccessStatusCode)
               {
                   return await rm.Content.ReadAsStringAsync();
               }
               return "No response";
           }
       }


Then, I changed my code and tried this one:

public async Task<string> Login()
      {
          HttpClient httpClient = new HttpClient();
          HttpRequestMessage request = new HttpRequestMessage();
          request.RequestUri = new Uri("my url and service");
          request.Method = HttpMethod.Get;
          request.Headers.Add("email", "my email");
          request.Headers.Add("api_key", "my key");
          HttpResponseMessage response = await httpClient.SendAsync(request);
          var responseString = await response.Content.ReadAsStringAsync();
          var statusCode = response.StatusCode;
          return statusCode.ToString();
      }


But also no any response except keep loading the page, in debug mode it reach to this line:
HttpResponseMessage response = await httpClient.SendAsync(request);


Any ideas?
--------------------
edit:
--------------------
It was a problem in my code, this is the correct code:

HttpClient httpClient = new HttpClient();
HttpRequestMessage request = new HttpRequestMessage();
request.RequestUri = new Uri("my url");
request.Method = HttpMethod.Post;
request.Headers.Add("email", "my email");
request.Headers.Add("api_key", "my api_key");
HttpResponseMessage response = httpClient.SendAsync(request).Result;
var responseString =  response.Content.ReadAsStringAsync();
Posted
Updated 15-Apr-23 14:30pm
v2
Comments
[no name] 12-Apr-23 12:46pm    
Use strings (with values) instead of literals. You really can't keep track of your parameters any other way (which is probably the issue).
Ahmad Yousef 2021 14-Apr-23 5:09am    
I tried to pass variables to function, same results...
mtoha 12-Apr-23 21:21pm    
are you sure post parameters sent is api_key and email?
are you sure with your url?
Ahmad Yousef 2021 14-Apr-23 5:10am    
Yes, the request header must contain email and api_key
Graeme_Grant 15-Apr-23 1:48am    
You should not be doing this for multiple reasons, resources will deplete.
HttpClient httpClient = new HttpClient();

Use IHttpClientFactory.

I mentioned above that you should use IHttpFactory. Here is a minimal implementation (.Net 3.1+):
C#
IHttpClientFactory InitializeHttpClientFactory()
{
    ServiceCollection builder = new();

    builder.AddHttpClient();

    ServiceProvider serviceProvider = builder.BuildServiceProvider();
    return serviceProvider.GetRequiredService<IHttpClientFactory>();
}

Then you can store a concrete implementation:
C#
IHttpClientFactory _httpClientFactory = InitializeHttpClientFactory();

and to use:
C#
using HttpClient client = _httpClientFactory!.CreateClient();

UPDATE
Here: NuGet Gallery | Microsoft.Extensions.Http 8.0.0-preview.3.23174.8[^] (edit: you can use other versions other than 8.0.0.0 preview, just what Google found)

Also, if your IDE is complaining: NuGet Gallery | Microsoft.Extensions.DependencyInjection 7.0.0[^]
 
Share this answer
 
v3
Comments
Ahmad Yousef 2021 15-Apr-23 20:25pm    
My code is working now, but I want to use this, what nuget package I shall use for IHttpClientFactory class please... is it Microsoft.Extensions.Http 7.0.0?
Graeme_Grant 15-Apr-23 20:31pm    
See the update.
Ahmad Yousef 2021 16-Apr-23 4:05am    
I did some changes, it worked after that using Microsoft.Extensions.Http 7.0.0, like:

public static IHttpClientFactory InitializeHttpClientFactory()


public static IHttpClientFactory _httpClientFactory = InitializeHttpClientFactory();

HttpClient httpClient = _httpClientFactory.CreateClient();
Graeme_Grant 16-Apr-23 4:12am    
There is an error in your last post:
HttpClient httpClient = new HttpClient();

should be:
using HttpClient client = _httpClientFactory.CreateClient();

or:
using HttpClient client = _httpClientFactory.CreateClient()
{
    // do work here
}

BTW, nowhere did you mention which version of .Net you were working with. This was fixing your memory leak / OS resource consumption issue. The code was pulled from a working console app written in .Net 7 ... for older .Net Framework 4, yes, they need to be static when used in a console add in the program class ... vote of 3 because of no static keyword is a bit underhanded. The code fixes your poor implementation, regardless of the 'static' keyword. If wrapped in a handler class, no static keyword would be used.
Ahmad Yousef 2021 16-Apr-23 10:47am    
I'm working on asp.net webform...
Unfortunately "using" statement didn't work...
vote of 3 because my problem was different and I've solved it, but you have assisted me in this new way, and I'm grateful!
try to use this functions:

C#
public async Task<M> ConnectHttpClient<R, M>(string apiUrl, R reqModel)
{
    M model = default(M);

    HttpClient client = new HttpClient();
    client.BaseAddress = new Uri(baseUrl);
    client.DefaultRequestHeaders.Accept.Clear();
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    HttpResponseMessage response = await client.PostAsJsonAsync(apiUrl, reqModel);
    if (response.IsSuccessStatusCode)
    {
        var res = response.Content.ReadAsStringAsync().Result;
        model = JsonConvert.DeserializeObject<M>(res);
    }
    return model;
}

public async Task<M> ConnectRestClient<R, M>(string apiUrl, R reqModel)
        {
            M model = default(M);

            RestClient restClient = new RestClient(apiUrl);
            RestRequest restRequest = new RestRequest(apiUrl, RestSharp.Method.Post);
            restRequest.AddParameter(
               "application/json",
               JsonConvert.SerializeObject(reqModel),
               ParameterType.RequestBody);
            RestResponse restResponse = await restClient.ExecuteAsync(restRequest);
            if (restResponse.IsSuccessful)
            {
                string response = restResponse.Content;
                model = JsonConvert.DeserializeObject<M>(response);
            }
            return model;
        }


example usage :
//example code
var result1 = await service.ConnectHttpClient<User, List<User>>("api/User/GetUserInfoByUserId", new User() { UserId = 1 });
var result2 = await service.ConnectRestClient<User, List<User>>("api/User/GetUserInfoByUserId", new User() { UserId = 1 });
 
Share this answer
 
v2
Comments
Ahmad Yousef 2021 14-Apr-23 5:12am    
This didn't work also
mtoha 14-Apr-23 5:14am    
that request have no header, you should add it by custom above method.
And I want to see what is the response of the request and how you try it? What you passed at function.
Ahmad Yousef 2021 14-Apr-23 5:31am    
The second function didn't work, I've tried RestClient then RestSharp nuget packages, but it still didn't acknowledge RestClient class...

mtoha 14-Apr-23 5:49am    
second function using restSharp, and some methods is deprecated. You can also try this
public async Task<m> ConnectRestClient<r, m="">(string apiUrl, R reqModel)
{
M model = default(M);

RestClient restClient = new RestClient(apiUrl);
RestRequest restRequest = new RestRequest(apiUrl, RestSharp.Method.Post);
restRequest.AddParameter(
"application/json",
JsonConvert.SerializeObject(reqModel),
ParameterType.RequestBody);
RestResponse restResponse = await restClient.ExecuteAsync(restRequest);
if (restResponse.IsSuccessful)
{
string response = restResponse.Content;
model = JsonConvert.DeserializeObject<m>(response);
}
return model;
}
Ahmad Yousef 2021 14-Apr-23 6:14am    
Same thing, error in RestClient class.
What I did is remove await from this line HttpResponseMessage response = await httpClient.SendAsync(request); and the problem solved, thank you for your time...
The two pieces of code you show are not equivalent. In the first instance, you pass the parameters as a post body. In the second instance, you add them as headers to a GET request. Which is it? Are they headers on a get or are they a post body? Is the API you are trying to connect to, accessible with the verb you are using?

If I were you, I would try the API call out outside of code first. Download Postman and use that to test the API call. Once you have it successfully working, you will know what to set in your code.
 
Share this answer
 
Comments
Ahmad Yousef 2021 15-Apr-23 2:24am    
I've started from testing on Postman, so I was assured it was a mistake in my code, your note is correct it's post not get, I'll edit my code to write the correct one. thanks for your comment.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900