50863

HttpClient is not posting form data

Question:

Can anyone tell me why is the PostAsync of the HttpClient is not posting the form data?

I'm getting no data on the server side at the time of this client posting. Last time I checked, the formFields contains data in key-value pairs but not able to find data in formContent.

using (var client = new HttpClient()) { var formFields = new List<KeyValuePair<string, string>>(); formFields.Add(new KeyValuePair<string, string>("AccountId", _dealerAccountId)); formFields.Add(new KeyValuePair<string, string>("Username", _dealerUsername)); formFields.Add(new KeyValuePair<string, string>("Password", _dealerPassword)); var formContent = new FormUrlEncodedContent(formFields); var response = await client.PostAsync(httpPrefix + "://" + httpHost + "/WebApi/Token/GetToken_v1/1592673/", formContent); if (!response.IsSuccessStatusCode) { return; } var responseContent = await response.Content.ReadAsStringAsync(); token = JsonConvert.DeserializeObject<string>(responseContent); }

Answer1:

I vaguely remembering having a similar issue. We ended up not using the "PostAsync" method but used the following. This is a helper method we use for testing our WebAPI. Hope this helps.

public async Task<TestHttpResponseMessage> Post(string url, string jsonPayload = "", Dictionary<string, string> headers = null, IFilter filter = null, HttpContent content = null) { using (var server = CreateTestserver(filter)) { if (!url.StartsWith("http")) url = "http://localhost/" + url; var request = new HttpRequestMessage { RequestUri = new Uri(url), Method = HttpMethod.Post, Content = content ?? new StringContent(jsonPayload, Encoding.UTF8, "application/json") }; request.Headers.Add("usertoken", OpenApiApplication.TestApiKey.ToString()); if (headers == null) headers = new Dictionary<string, string>(); foreach (var header in headers) request.Content.Headers.Add(header.Key, header.Value); var httpResponseMessage = await server.HttpClient.SendAsync(request); var stringResult = await httpResponseMessage.Content.ReadAsStringAsync(); return new TestHttpResponseMessage { JsonObject = Json.Decode(stringResult), HttpResponseMessage = httpResponseMessage }; } }

Recommend

  • spring websocket with digest authentication
  • Caused by: java.lang.IllegalArgumentException: Host name may not be null
  • Java httpclient 4.1 how to send post request with configurable port
  • Url Rewrite - Web.config - HTTPS and www
  • Conscrypt with jdk8 to enable ALPN for http2
  • ElasticSearch JavaAPI RestClient not giving response
  • Order C# list alphabetically
  • Access HttpConfiguration in Orchard CMS
  • Cross- origin request
  • Asynchronously Load Image from URL into ImageView in Xamarin Android
  • Image loaded from Isolated storage are not binding at all
  • ADAL js does not work in IE when acquiring token for remote endpoint when website url is added to “T
  • Angular 2 - What to do when an Http request depends on result of another Http request
  • jQuery callback called twice
  • How to set a URL scheme/link for a react-native app
  • Split string that used to be a list
  • Setting Django secret key in environment variable fails due to special character
  • Easy way to serialize/deserialize public enums?
  • Apple Pay using Stripe send token to server and charge for purchase
  • Configurable Windows Service - How and where to store configuration
  • Dynamic JavaScript returned by webapi
  • Login to adfs through openam using java application
  • Custom thread pool supporting async actions
  • Web API Routing - No action was found on the controller that matches the request
  • Force user change password after first login asp.net mvc with Forms authentication
  • Syntax error near unexpected token `(' with mv !(build)
  • Azure AD: How to get group information in token?
  • Using RegEx in View
  • How to enumerate Azure subscriptions and tenants programmatically?
  • Property 'catch' does not exist on type 'PromiseLike
  • AntiForgery Token implementation in Angular 2 and Web Api using Aps.Net Core
  • Task.IsCancelled doesn't work
  • Optimising asyncronus HttpClient requests
  • Success handler not working after Symfony2 login
  • Migration tool for ANTLR grammar
  • IDX10503: Signature validation failed
  • oauth2client.client.HttpAccessTokenRefreshError: invalid_grant: Invalid JWT
  • Syntax error near unexpected token 'elif'
  • How dotnet build chooses the output name
  • read values from form post in jquery or javascript