相关文章推荐
至今单身的保温杯  ·  Android 休眠(一) ...·  3 月前    · 
机灵的木瓜  ·  (操作系統錯誤 10054) ...·  8 月前    · 
呐喊的小蝌蚪  ·  .Net Core WPF ...·  10 月前    · 
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(); I mentioned above that you should use IHttpFactory . Here is a minimal implementation (.Net 3.1+):
IHttpClientFactory InitializeHttpClientFactory() ServiceCollection builder = new (); builder.AddHttpClient(); ServiceProvider serviceProvider = builder.BuildServiceProvider(); return serviceProvider.GetRequiredService<IHttpClientFactory>(); Then you can store a concrete implementation:
IHttpClientFactory _httpClientFactory = InitializeHttpClientFactory();
and to use:
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 [ ^ ]
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.
Asp.Net? Even more reason to change to IHttpClientFactory . If not your website will crash. A bigger problem & solution to the issue that you are having! This would have been even harder to resolve.

Look at the 2nd example for the Using statement. The first version is a modern C#11 syntax. The Using statement is to prevent memory leaks. If not using the Using statement, then you need to manually dispose with
client.Dispose();


As for the original issue that you have asked for help with, there is not enough information given to answer the question asked. We have no idea of the requirements for the API that you are trying to connect to.
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 });
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;
}
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.
  • Read the question carefully.
  • Understand that English isn't everyone's first language so be lenient of bad spelling and grammar.
  • If a question is poorly phrased then either ask for clarification, ignore it, or edit the question and fix the problem. Insults are not welcome.
  • Don't tell someone to read the manual. Chances are they have and don't get it. Provide an answer or move on to the next question. Let's work to help developers, not make them feel stupid.
  •