How to get object using Httpclient with response Ok in Web Api - c#

my web api like
public async Task<IHttpActionResult> RegisterUser(User user)
{
//User Implementation here
return Ok(user);
}
I am using HTTPClient to request web api as mentioned below.
var client = new HttpClient();
string json = JsonConvert.SerializeObject(model);
var result = await client.PostAsync( "api/users", new StringContent(json, Encoding.UTF8, "application/json"));
Where i can find user object in my result request which is implemented on client application?

You can use (depands on what you need), and de-serialize it back to user object.
await result.Content.ReadAsByteArrayAsync();
//or
await result.Content.ReadAsStreamAsync();
//or
await result.Content.ReadAsStringAsync();
Fe, if your web api is returning JSON, you could use
var user = JsonConvert.DeserializeObject<User>( await result.Content.ReadAsStringAsync());
EDIT:
as cordan pointed out, you can also add reference to System.Net.Http.Formatting and use:
await result.Content.ReadAsAsync<User>()

string Baseurl = GetBaseUrl(microService);
string url = "/client-api/api/token";
using (HttpClient client = new HttpClient())`enter code here`
{
client.BaseAddress = new Uri(Baseurl);
client.DefaultRequestHeaders.Clear();
client.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/x-www-form-urlencoded");
List<KeyValuePair<string, string>> keyValues = new List<KeyValuePair<string, string>>();
keyValues.Add(new KeyValuePair<string, string>("client_id", "5196810"));
keyValues.Add(new KeyValuePair<string, string>("grant_type", "password"));
keyValues.Add(new KeyValuePair<string, string>("username", "abc.a#gmail.com"));
keyValues.Add(new KeyValuePair<string, string>("password", "Sonata#123"));
keyValues.Add(new KeyValuePair<string, string>("platform", "FRPWeb"));
HttpContent content = new FormUrlEncodedContent(keyValues);
content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
content.Headers.ContentType.CharSet = "UTF-8";
var result = client.PostAsync(url, content).Result;
string resultContent = result.Content.ReadAsStringAsync().Result;
}

Related

Send form-data in C# HttpClient

Hello, I am pulling data from an api with C# HttpClient. I need to pull data in form-data form with the post method. I wrote the code below but got an empty response. How can I do it?
var client = new HttpClient();
client.Timeout = TimeSpan.FromSeconds(300);
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
var request = new HttpRequestMessage();
request.Method = HttpMethod.Post;
request.RequestUri = new Uri("https://myapi.com");
var content = new MultipartFormDataContent();
var dataContent = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("value1", "myvalue1"),
new KeyValuePair<string, string>("value2", "myvalue2"),
new KeyValuePair<string, string>("value3", "myvalue3")
});
content.Add(dataContent);
request.Content = content;
var header = new ContentDispositionHeaderValue("form-data");
request.Content.Headers.ContentDisposition = header;
var response = await client.PostAsync(request.RequestUri.ToString(), request.Content);
var result = response.Content.ReadAsStringAsync().Result;
You're sending your data in an incorrect way by using FormUrlEncodedContent.
To send your parameters as MultipartFormDataContent string values you need to replace the code below:
var dataContent = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("key1", "myvalue1"),
new KeyValuePair<string, string>("key2", "myvalue2"),
new KeyValuePair<string, string>("key3", "myvalue3")
});
With this:
content.Add(new StringContent("myvalue1"), "key1");
content.Add(new StringContent("myvalue2"), "key2");
content.Add(new StringContent("myvalue3"), "key3");

c# post request using httpparams and headers

I had a client app which was written in angular that post requests to connect/token
const body = new HttpParams()
.set('username', email)
.set('password', password)
.set('grant_type', "password")
.set('scope', "offline_access");
const headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded');
return this.http.post<any>(this._baseAuthUrl + 'connect/token', body, { headers })
Now I have to write this in c#, but stuck with some part
HttpClient httpClient = new HttpClient();
HttpRequestMessage requestMessage = new HttpRequestMessage(HttpMethod.Post, "http://mysite/connect/token");
requestMessage.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
How do I add HttpParams and post request properly please?
Here is the code.
var httpClient = new HttpClient();
var pairs = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("username", email),
new KeyValuePair<string, string>("password", password),
new KeyValuePair<string, string>("grant_type", "password"),
new KeyValuePair<string, string>("scope", "offline_access")
};
var content = new FormUrlEncodedContent(pairs);
HttpRequestMessage requestMessage = new HttpRequestMessage(HttpMethod.Post, "http://mysite/connect/token");
requestMessage.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
requestMessage.Content = content;
var response = await httpClient.SendAsync(requestMessage);
The above code is just an example to answer the question. But in your implementation, You should use HttpClient static and initialize it at once. Read more

I am not getting response REST API (POST) Content Type FormUrlEncode

When I try in postman it working fine and I am getting a response.
I am trying to make a request. and I am not getting any response please look into my code and let me know where I did wrong?
using (var client = new HttpClient())
{
var content = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("client_id", "11223asda"),
new KeyValuePair<string, string>("client_secret", "1232asdasa"),
new KeyValuePair<string, string>("code", "authcode3"),
new KeyValuePair<string, string>("grant_type", "authorization_code"),
new KeyValuePair<string, string>("redirect_uri", "http://www.google.com/")
});
var uri = new Uri("https://sandbox-api.userdomain.com/v2/oauth2/token");
// var content = new FormUrlEncodedContent(obj);
//HttpResponseMessage response = null;
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, uri);
request.Content = content;
HttpResponseMessage response = await client.SendAsync(request);
Debug.WriteLine(response.StatusCode);
Output :
For this type of work I use this lib :
https://github.com/jgiacomini/Tiny.RestClient
var client = new TinyRestClient(new HttpClient(),"https://sandbox-api.userdomain.com/");
var response = await client.
PostRequest("v2/oauth2/token").
AddFormParameter("client_id", "France").
AddFormParameter("client_secret", "Paris").
AddFormParameter("grant_type", "Paris").
AddFormParameter("redirect_uri", "Paris").
ExecuteAsync<Response>();
Hope that helps!

Not Response get access token oauth 2.0 API UBER in ASP NET C#

I'm using this method, I recover the error "The interruption of an existing connection has been forced by the remote host"
public static async void GetAccessToken()
{
var client = new HttpClient();
// Create the HttpContent for the form to be posted.
var requestContent = new FormUrlEncodedContent(
new[] {
new KeyValuePair<string, string>("client_secret","xxxxx"),
new KeyValuePair<string, string>("client_id","xxxxx"),
new KeyValuePair<string, string>("grant_type","authorization_code"),
new KeyValuePair<string, string>("redirect_uri","http://localhost"),
new KeyValuePair<string, string>("code","xxxxx")
});
// Get the response.
HttpResponseMessage response = await client.PostAsync(
"https://domain-uber.com/oauth/v2/token",
requestContent);
// Get the response content.
HttpContent responseContent = response.Content;
// Get the stream of the content.
using (var reader = new StreamReader(await responseContent.ReadAsStreamAsync()))
{
var result = await reader.ReadToEndAsync();
}
}

How to POST using HTTPclient content type = application/x-www-form-urlencoded

I am currently developing a wp8.1 application C#, i have managed to perform a POST method in json to my api by creating a json object (bm) from textbox.texts.
here is my code below. How do i take the same textbox.text and POST them as a content type = application/x-www-form-urlencoded. whats the code for that?
Profile bm = new Profile();
bm.first_name = Names.Text;
bm.surname = surname.Text;
string json = JsonConvert.SerializeObject(bm);
MessageDialog messageDialog = new MessageDialog(json);//Text should not be empty
await messageDialog.ShowAsync();
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/json");
byte[] messageBytes = Encoding.UTF8.GetBytes(json);
var content = new ByteArrayContent(messageBytes);
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
var response = client.PostAsync("myapiurl", content).Result;
var nvc = new List<KeyValuePair<string, string>>();
nvc.Add(new KeyValuePair<string, string>("Input1", "TEST2"));
nvc.Add(new KeyValuePair<string, string>("Input2", "TEST2"));
var client = new HttpClient();
var req = new HttpRequestMessage(HttpMethod.Post, url) { Content = new FormUrlEncodedContent(nvc) };
var res = await client.SendAsync(req);
Or
var dict = new Dictionary<string, string>();
dict.Add("Input1", "TEST2");
dict.Add("Input2", "TEST2");
var client = new HttpClient();
var req = new HttpRequestMessage(HttpMethod.Post, url) { Content = new FormUrlEncodedContent(dict) };
var res = await client.SendAsync(req);
var params= new Dictionary<string, string>();
var url ="Please enter URLhere";
params.Add("key1", "value1");
params.Add("key2", "value2");
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = client.PostAsync(url, new FormUrlEncodedContent(params)).Result;
var token = response.Content.ReadAsStringAsync().Result;
}
//Get response as expected
The best solution for me is:
// Add key/value
var dict = new Dictionary<string, string>();
dict.Add("Content-Type", "application/x-www-form-urlencoded");
// Execute post method
using (var response = httpClient.PostAsync(path, new FormUrlEncodedContent(dict))){}
Another variant to POST this content type and which does not use a dictionary would be:
StringContent postData = new StringContent(JSON_CONTENT, Encoding.UTF8, "application/x-www-form-urlencoded");
using (HttpResponseMessage result = httpClient.PostAsync(url, postData).Result)
{
string resultJson = result.Content.ReadAsStringAsync().Result;
}

Categories