0
I am trying to consume a third party webservice in my controller, but I need to do an authentication with username and password and pass another parameter in the POST but in every way I did returns error 400 as if my parameters were not going, Does anyone have an example for me? I’m using aspnet core 1.0
For example, this was a method I tried:
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(apiBaseUri);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var formContent = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("grant_type", "client_credentials"),
new KeyValuePair<string, string>("username", userName),
new KeyValuePair<string, string>("password", password),
});
//send request
HttpResponseMessage responseMessage = await client.PostAsync("/token", formContent);
if(responseMessage.StatusCode == HttpStatusCode.OK)
{
//get access token from response body
var responseJson = await responseMessage.Content.ReadAsStringAsync();
var jObject = JObject.Parse(responseJson);
return jObject.GetValue("access_token").ToString();
}
else
{
return null;
}
}
This is the error that presents:
{StatusCode: 400, ReasonPhrase: 'Bad Request', Version: 1.1, Content: System.Net.Http.StreamContent, Headers: { Connection: close Connection: close Date: Tue, 25 Oct 2016 12:21:53 GMT Server: Apache Set-Cookie: X-PP-SILOVER=name%3DSANDBOX3.API.1%26silo_version%3D1880%26app%3Dplatformapiserv%26TIME%3D1632505688%26HTTP_X_PP_AZ_LOCATOR%3D; Expires=Tue, 25 Oct 2016 12:51:53 GMT; domain=.paypal.com; path=/; Secure; HttpOnly Set-Cookie: X-PP-SILOVER=; Expires=Thu, 01 Jan 1970 00:00:01 GMT PROXY_SERVER_INFO: host=slcsbplatformapiserv3001.slc.paypal.com;threadId=842 Paypal-Debug-Id: 41e81ada72ff1 Paypal-Debug-Id: 41e81ada72ff1 CORRELATION-ID: 41e81ada72ff1 X-PAYPAL-TOKEN-SERVICE: IAAS Content-Length: 79 Content-Type: application/json }}
And the code generated by Postman with Restsharp is:
var client = new RestClient(uri);
var request = new RestRequest(Method.POST);
request.AddHeader("postman-token", token);
request.AddHeader("cache-control", "no-cache");
request.AddHeader("authorization", "Basic username:password");
request.AddHeader("content-type", "application/x-www-form-urlencoded");
request.AddParameter("application/x-www-form-urlencoded", "grant_type=client_credentials", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);`
it would also be nice to see what you have already tried to do. Third Party Webservice Rest has no manual?
– novic
edited the code so you can see how I tried to do, thanks for the help
– Diogo Soares
Error 400 means Bad Request, that is, the server could not fulfill the request due to invalid syntax.
– Marconi