Reputation: 1874
I am working on rest Services which is a external travel portal api which talks in json format. I want to create an action method to post username and password to this api url. I am able to do it in fiddler but dont know how to transmit information in web api action method.this url will return back a token id which i will be used for all sub request. My questions--
I am passing username and password from view page to controller through formCollection. I want to know how to add jsonArray with credentials to this request headers and get back the response back.
[HttpPost]
public IHttpActionResult About(FormCollection form)
{
string url = "http://someurl.com//api/PersonalDetails/GetPersonalDetails";
using (HttpClient client = new HttpClient())
{
client.BaseAddress = new Uri(url);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new
Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
}
The json array is something like this:
{
"ClientId": "ApiIntegration",
"UserName": "xxxxxx",
"Password": "xxxxxx@12",
"EndUserIp": "192.168.11.120"
}
I want to send this array with parameters to this url. but dont know how to do it. I was trying to create anonymous method and pass value to request headers. Trying something like this:
var arr = new
{
ClientId = "ApiIntegration",
UserName = Convert.ToString(form["UserName"].ToString()),
Password = Convert.ToString(form["Password"].ToString()),
EndUserIp = "192.168.11.120"
};
In fiddler,it was very simple. i have simply put all credentials in Response body and in Request Headers, set the Content-Type to application/json and get back all the data.
Please help me someone.
Upvotes: 0
Views: 152
Reputation: 4000
If you simply want to post data to this endpoint:
string url = "http://someurl.com//api/PersonalDetails/GetPersonalDetails";
using (var client = new HttpClient())
{
var payload = JsonConvert.SerializeObject(new
{
ClientId = "ApiIntegration",
UserName = Convert.ToString(form["UserName"].ToString()),
Password = Convert.ToString(form["Password"].ToString()),
EndUserIp = "192.168.11.120"
});
var response = await client.PostAsync(url, new StringContent(payload, Encoding.UTF8, "application/json"));
var json = await response.Content.ReadAsStringAsync();
// deserialize the json and get your token id
}
Upvotes: 1