JSON POST to Sharepoint Using Graph Status Code 400 - c#

OK. So this is really starting to baffle me now. I can get this to work on one UWP app, but not this one.
I have this piece of code to post:
public async Task<string> SubmitDataWithTokenAsync(string url, string token)
{
var httpClient = new HttpClient();
HttpResponseMessage response;
try
{
var root = new
{
fields = new Dictionary<string, string>
{
//General Parameters...
//Inspection Parameters...
//Startup Parameters...
//Mechanical Parameters...
//Electrical Parameters...
//SCR Parameters...
//Shutdown Parameters...
}
};
var s = new JsonSerializerSettings { DateFormatHandling = DateFormatHandling.MicrosoftDateFormat };
var content = JsonConvert.SerializeObject(root, s);
var request = new HttpRequestMessage(HttpMethod.Post, url);
//Add the token in Authorization header
request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token);
request.Content = new StringContent(content, Encoding.UTF8, "application/json");
response = await httpClient.SendAsync(request);
var responseString = await response.Content.ReadAsStringAsync();
return responseString;
}
catch (Exception ex)
{
return ex.ToString();
}
}
}
the content comes back just fine, so it seems....
"{\"fields\":{\"Date\":\"8/16/2018 2:18:48 PM -04:00\",\"Maximo\":null,\"IBX\":\"DC4\",\"Generator\":\"Generator D\",\"AirQuality\":\"Red / Unhealthy\",\"Engineer\":\"Kassim Ganiyou\",\"MT1Level\":null,\"MT2Level\":null,\"StartDTLevel\":null,\"BC1V\":null,\"BC1A\":null,\"BC2V\":null,\"BC2A\":null,\"StartCoolantTEmp\":null,\"StartHours\":null,\"Reason\":null,\"InspectionNotes\":null,\"StartTime\":null,\"CrankV1\":null,\"CrankV2\":null,\"Emissions\":null,\"SCRStartTime\":null,\"OilPressure\":null,\"CoolantTemp\":null,\"BatteryVolt\":null,\"LeftExhTemp\":null,\"RightExhTemp\":null,\"ABVolts\":null,\"BCVolts\":null,\"CAVolts\":null,\"AAmps\":null,\"BAmps\":null,\"CAmps\":null,\"KW\":null,\"Frequency\":null,\"SCROutletTemp\":null,\"NOx\":null,\"UReaFLow\":null,\"Alarms\":null,\"SCRSTopTime\":null,\"StopTime\":null,\"StopHours\":null}}"
The request comes back:
{Method: POST, RequestUri: 'https://graph.microsoft.com/v1.0/sites/root/lists/A07CEC93-XXXX-XXXX-XXXX-0F756D2EF63A/items', Version: 2.0, Content: System.Net.Http.StringContent, Headers:
{
Authorization: Bearer eyJ0eX...PUQ
Content-Type: application/json; charset=utf-8
Content-Length: 603
}}
But then the response is:
{StatusCode: 400, ReasonPhrase: 'Bad Request', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
client-request-id: bb26e6fe-4fae-41ae-921d-aeb39063bd8e
Strict-Transport-Security: max-age=31536000
request-id: bb26e6fe-4fae-41ae-921d-aeb39063bd8e
Transfer-Encoding: chunked
x-ms-ags-diagnostic: {"ServerInfo":{"DataCenter":"East US","Slice":"SliceC","Ring":"5","ScaleUnit":"001","Host":"AGSFE_IN_1","ADSiteName":"EUS"}}
Duration: 319.5961
Cache-Control: private
Date: Thu, 16 Aug 2018 20:03:10 GMT
Content-Type: application/json
}}
I have another UWP app going to the same sharepoint site and I get a Status 201 no problem. I am just not seeing where my issue is in this case.

This is why it is good to take a break from a project and come back to it later.
I found out that I had mistyped ONE letter on the SharePoint list. So today when I reviewed the response code it pointed it our to me.
The code WAS good.
Thanks all.

Related

How to fix C# code to push folder to GitHub repository

I am attempting to develop a WinUI 3 application to push the files in a folder on my local machine to an existing private GitHub repository. However, I when run the code shown below, nothing gets pushed to GitHub.
public async Task PushFolderToGitHub()
{
string folderPath = "C:\\TestFolder"
string repoOwner = "my_github_username";
string repoName = "my_repo_name";
string token = "my_github_PAT";
var baseAddress = "https://api.github.com";
var client = new HttpClient { BaseAddress = new Uri(baseAddress) };
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue("MyApp", "1.0"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Token", token);
var rootFolder = await StorageFolder.GetFolderFromPathAsync(folderPath);
var files = await rootFolder.GetFilesAsync();
foreach (var file in files)
{
var content = new StringContent(System.IO.File.ReadAllText(file.Path), Encoding.UTF8, "text/plain");
var path = $"{rootFolder.Name}/{file.Name}";
var requestUri = $"/repos/{repoOwner}/{repoName}/contents/{path}";
try
{
var response = await client.PutAsync(requestUri, content);
response.EnsureSuccessStatusCode();
var responseString = await response.Content.ReadAsStringAsync();
Debug.WriteLine(responseString);
}
catch (Exception ex)
{
// Log the exception or display an error message
Debug.WriteLine(ex.Message);
return;
}
}
}
I debugged this, and found that the line var response = await client.PutAsync(requestUri, content); returned the following value for "response":
response {StatusCode: 403, ReasonPhrase: 'Forbidden', Version: 1.1, Content: System.Net.Http.HttpConnectionResponseContent, Headers:
{
Cache-Control: no-cache
Strict-Transport-Security: max-age=31536000
X-Content-Type-Options: nosniff
X-Frame-Options: DENY
X-XSS-Protection: 0
Content-Security-Policy: default-src 'none'; style-src 'unsafe-inline'
Connection: close
Content-Type: text/html; charset=utf-8
}} System.Net.Http.HttpResponseMessage
I have double checked that my username and PAT are correct, so I do not understand why this is happening. If anyone could share any ideas on how I could fix this, then I would greatly appreciate it.
Update: On doing some further research I found that all GitHub API calls must include the User Agent header, so I added the following line of code as shown above: client.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue("MyApp", "1.0"));. As a result the value for response is now as follows:
- response {StatusCode: 404, ReasonPhrase: 'Not Found', Version: 1.1, Content: System.Net.Http.HttpConnectionResponseContent, Headers:
{
Server: GitHub.com
Date: Thu, 16 Feb 2023 07:00:12 GMT
X-OAuth-Scopes: admin:enterprise, admin:gpg_key, admin:org, admin:org_hook, admin:public_key, admin:repo_hook, admin:ssh_signing_key, audit_log, codespace, delete:packages, delete_repo, gist, notifications, project, repo, user, workflow, write:discussion, write:packages
X-Accepted-OAuth-Scopes: repo
github-authentication-token-expiration: 2023-03-13 12:19:42 UTC
X-GitHub-Media-Type: github.v3
x-github-api-version-selected: 2022-11-28
X-RateLimit-Limit: 5000
X-RateLimit-Remaining: 4973
X-RateLimit-Reset: 1676532832
X-RateLimit-Used: 27
X-RateLimit-Resource: core
Access-Control-Expose-Headers: ETag, Link, Location, Retry-After, X-GitHub-OTP, X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Used, X-RateLimit-Resource, X-RateLimit-Reset, X-OAuth-Scopes, X-Accepted-OAuth-Scopes, X-Poll-Interval, X-GitHub-Media-Type, X-GitHub-SSO, X-GitHub-Request-Id, Deprecation, Sunset
Access-Control-Allow-Origin: *
Strict-Transport-Security: max-age=31536000; includeSubdomains; preload
X-Frame-Options: DENY
X-Content-Type-Options: nosniff
X-XSS-Protection: 0
Referrer-Policy: origin-when-cross-origin, strict-origin-when-cross-origin
Content-Security-Policy: default-src 'none'
Vary: Accept-Encoding, Accept, X-Requested-With
X-GitHub-Request-Id: 1826:0605:C27EE8:D02D1B:63EDD47C
Content-Type: application/json; charset=utf-8
Content-Length: 74
}} System.Net.Http.HttpResponseMessage
I have double checked the repoOwner and repoName variables, so I am unsure why this is returning a 404 error. SO once again, if anyone has any ideas, I would greatly appreciate it.

Google API Oauth2 Refresh token bad request 400

having an issue refreshing an existing token by using the Google API with Xamarin C#. I guess something is wrong with my code, but I cannot find what.
(Note: I added newline characters at the & to make the requests more readable. Hope everyone will be cool with that.)
Request Auth URI
https://accounts.google.com/o/oauth2/v2/auth?
scope=https://www.googleapis.com/auth/calendar https://www.googleapis.com/auth/calendar.events&
include_granted=true&
response_type=code&
redirect_uri=com.googleusercontent.apps.MYOAUTHCLIENTID:/oauth2redirect&
client_id=MYOAUTHCLIENTID.apps.googleusercontent.com&
access_type=offline
Redirect URI
com.googleusercontent.apps.MYOAUTHCLIENTID:/oauth2redirect
Response Authentication Code
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
Request token URI
https://oauth2.googleapis.com/token?
code=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX&
redirect_uri=com.googleusercontent.apps.MYOAUTHCLIENTID:/oauth2redirect&
client_id=MYOAUTHCLIENTID.apps.googleusercontent.com&
grant_type=authorization_code
Response token
{
"access_token": "YYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY",
"expires_in": 3599,
"refresh_token": "ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ",
"scope": "https://www.googleapis.com/auth/calendar https://www.googleapis.com/auth/calendar.events",
"token_type": "Bearer"
}
Now I can use the "access_token" in my HTTP header requests and work with the calendar without problems. I also can revoke the token, but not refreshing it.
Try to refresh token
var dict = new Dictionary<string, string>();
dict.Add("Content-Type", "application/x-www-form-urlencoded");
var contentHeader = new FormUrlEncodedContent(dict);
HttpClient refreshTokenClient = new HttpClient();
// Doing this because someone wrote that this helped in his case. Did not help :/
System.Net.ServicePointManager.SecurityProtocol |=
SecurityProtocolType.Tls12 |
SecurityProtocolType.Tls11 |
SecurityProtocolType.Tls;
// uriTokenRequest has the type URI with this value
// {https://oauth2.googleapis.com/token?
// code=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX&
// client_id=MYOAUTHCLIENTID.apps.googleusercontent.com&
// grant_type=refresh_token&
// refresh_token=ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ}
using (var result = await refreshTokenClient.PostAsync(uriTokenRequest, contentHeader))
if (result.IsSuccessStatusCode) // This will be FALSE
{
...
}
The response
{StatusCode: 400, ReasonPhrase: 'Bad Request', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
Accept-Ranges: none
Alt-Svc: h3=":443"; ma=2592000,h3-29=":443"; ma=2592000,h3-T051=":443"; ma=2592000,h3-Q050=":443"; ma=2592000,h3-Q046=":443"; ma=2592000,h3-Q043=":443"; ma=2592000,quic=":443"; ma=2592000; v="46,43"
Cache-Control: no-store, must-revalidate, no-cache, max-age=0
Date: Sun, 11 Jul 2021 13:46:09 GMT
Pragma: no-cache
Server: scaffolding
Server: on
Server: HTTPServer2
Transfer-Encoding: chunked
Vary: X-Origin
Vary: Referer
Vary: Origin
Vary: Accept-Encoding
X-Android-Received-Millis: 1626011170088
X-Android-Response-Source: NETWORK 400
X-Android-Selected-Protocol: http/1.1
X-Android-Sent-Millis: 1626011170050
X-Content-Type-Options: nosniff
X-Frame-Options: SAMEORIGIN
X-XSS-Protection: 0
Content-Type: application/json; charset=utf-8
Expires: Mon, 01 Jan 1990 00:00:00 GMT
}}
The Google API documentation https://developers.google.com/identity/protocols/oauth2/native-app#offline does say about a "client_secret". But with the response_type "code" I never received such. I've read the documentation now so many times that I am blind to it.
Or does "code" not require a token refresh?
Any ideas?
EDIT: "code" does require a token refresh, since the token does expire, as the result property "expires_in" already tell.
EDIT 2: As by Cherry Bu - MSFT suggested I peeked at the Xamarin.Auth source code and found some differences, that I adapted. Unfortunately I am still not able to succeed. This is my latest try:
var queryValues = new Dictionary<string, string>();
//queryValues.Add("Content-Type", "application/x-www-form-urlencoded");
queryValues.Add("client_id", Constants.OAuthClientId);
queryValues.Add("code", _authenticationCode);
queryValues.Add("refresh_token", _refresh_token);
queryValues.Add("grant_type", "refresh_token");
var httpContent = new FormUrlEncodedContent(queryValues);
HttpClient refreshTokenClient = new HttpClient();
//if (!string.IsNullOrEmpty(_accessToken) && !string.IsNullOrEmpty(_accessTokenType))
//{
// refreshTokenClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(_accessTokenType, _accessToken);
//}
using (var response = await refreshTokenClient.PostAsync("https://accounts.google.com/o/oauth2/token", httpContent).ConfigureAwait(false))
{
if (response.IsSuccessStatusCode) --> This will be false
{
...
}
}
The correct http end point to refresh an access token can be found below
HTTP POST https://accounts.google.com/o/oauth2/token
client_id={ClientId}&client_secret={ClientSecret}&refresh_token=1/ffYmfI0sjR54Ft9oupubLzrJhD1hZS5tWQcyAvNECCA&grant_type=refresh_token
I actually have an example of using the google .net client library with Xamarin i had to adapt the authorization to it. I will have a look around see if i can find the code.
Fixed it. 2 issues:
1 The DefaultRequestHeader did not work.
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(GoogleOAuth.AccessToken, GoogleOAuth.AccessTokenType);
Even when the object itself did look alright it did not work. I replaced it with that:
HttpClient client = new HttpClient();
var requestMessage = new HttpRequestMessage(HttpMethod.Post, calenderUri);
requestMessage.Headers.Authorization = new AuthenticationHeaderValue(GoogleOAuth.AccessTokenType, GoogleOAuth.AccessToken); // both are strings. ("Bearer", "yaa...")
requestMessage.Content = data;
var response = await client.SendAsync(requestMessage);
if (!response.IsSuccessStatusCode)
{
string content = await response.Content.ReadAsStringAsync();
throw new Exception(content);
}
After that I only had to do one more thing
2 Removed "code" and "client_secret" from the request data. The result:
using (HttpClient client = new HttpClient())
{
var googleData = new Dictionary<string, string>();
googleData.Add("client_id", GoogleOAuth.ClientId);
googleData.Add("refresh_token", GoogleOAuth.RefreshToken);
googleData.Add("grant_type", "refresh_token");
var data = new FormUrlEncodedContent(googleData);
var requestMessage = new HttpRequestMessage(HttpMethod.Post, Constants.GoogleTokenUri);
requestMessage.Headers.Authorization = new AuthenticationHeaderValue(GoogleOAuth.AccessTokenType, GoogleOAuth.AccessToken);
requestMessage.Content = data;
var response = await client.SendAsync(requestMessage);
if (response.IsSuccessStatusCode)
{
// do something
}
}
For weeks I tried to get it running and was close to insanity. Hope this saves someones nerves.

Getting StatusCode: 401, ReasonPhrase: 'Unauthorized', Version: 1.1, Content: System.Net.Http.StreamContent, Headers error when Calling a API via code

I try to call an external api, when I am using the Postman, it is working and returning value as follows:
Post to URL: https://test.com/api/v1/users/check
Data Raw Jason to post:
{
"access_token":"4444-EA444B6-2844C7-A09C-44B05CA78E42A3",
"email":"test#test.com",
"create_user": true,
"first_name": "test4",
"last_name": "test",
"phone": 3104054512
}
So this is working and returning me response model.
but when try this code to call the api:
Controller:
[Route("CreateUser")]
public Task<UserReturn> CreateUser([FromBody] User user)
{
return homebirdRepository.CreateUser(user);
}
public async Task<UserReturn> CreateUser(User userCheck)
{
using (GetWSObject<UserReturn> addObjectInt = new GetWSObject<UserReturn>())
{
return await addObjectInt.PostWSObjectModel("api/v1/users/check", userCheck, "API_URI");
}
}
public async Task<T> PostWSObjectModel(string uriActionString, Object model, string apiKey)
{
T returnValue = default(T);
try
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(WebConfigurationManager.AppSettings[apiKey]);
var content = new StringContent(JsonConvert.SerializeObject(model));
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
HttpResponseMessage response = await client.PostAsync(uriActionString, content);
response.EnsureSuccessStatusCode();
var test = response.Content.ReadAsStringAsync().Result;
returnValue = JsonConvert.DeserializeObject<T>(((HttpResponseMessage)response).Content.ReadAsStringAsync().Result);
}
return returnValue;
}
catch (Exception e)
{
throw (e);
}
}
This code is returning me this error:
StatusCode: 401, ReasonPhrase: 'Unauthorized', Version: 1.1, Content:
System.Net.Http.StreamContent,
Headers:
{
Connection: keep-alive
Access-Control-Allow-Origin: *
Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-
With
Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS
Cache-Control: no-cache, private
Date: Sat, 28 Dec 2019 00:00:04 GMT
Set-Cookie:laravel_session=eyJpdiI6IlI2MUdzOFJmS0RcL1k1VmJCeTc4bk1nPT0iLCJ2YWx1ZSI6IlZXNW11MGw2bXk0ajFEaTM2VnhmbUZjQnFzdnRDRHV5ejJMaDRqTVJYQm1yclNyUUkweDNRMUhpZDZwblpES1MiLCJtYWMiOiI0NmFiODA4YzEyNTkxZDllNDViNGUwOGIzYjY2ZWYxZGQwNzI1NmZmYzYxYTBkZGU0M2NmMDBlYzIzN2E3OTFjIn0%3D; expires=Sat, 28-Dec-2019 02:00:04 GMT; Max-Age=7200; path=/; httponly
Server: Apache
Content-Length: 21
Content-Type: text/html; charset=UTF-8
}}
You most likely have a header, cookie, etc. that is not set in C# which is set in Postman. There are several ways you can determine which properties are being set in Postman. I've answered a similar question here. Fiddler or some other separate tool shouldn't be necessary.
you must add the Authorization header, this one is added and calculated by postman, you can copy/post. the following if you are using a Basic authentication.
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", "value to copy from postman");

Azure graph API / c# patch URL

I am attempting to write a password reset application c# and the graph API. I have set permissions for the application within Azure, receive a valid token, and can request information.
I am receiving a 400 Bad Request response when attempting to perform the reset. I believe I am forming the URL incorrectly. Here is the response I receive followed by my code.
Thanks in advance!
Response: StatusCode: 400, ReasonPhrase: 'Bad Request', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
Transfer-Encoding: chunked
request-id: omitted
client-request-id: omitted
x-ms-ags-diagnostic: {"ServerInfo":{"DataCenter":"North Central US","Slice":"SliceA","Ring":"3","ScaleUnit":"002","Host":"AGSFE_IN_29","ADSiteName":"CHI"}}
Duration: 43.0949
Strict-Transport-Security: max-age=31536000
Cache-Control: private
Date: Mon, 02 Apr 2018 18:06:06 GMT
Content-Type: application/json
}
private static async Task ResetPasswordAsync(HttpClient client, string UPN)
{
var payload = new
{
accountEnabled = true,
passwordProfile = new
{
forceChangePasswordNextSignIn = true,
password = "Password!"
}
};
var payloadJSON = JsonConvert.SerializeObject(payload);
Console.WriteLine(payloadJSON);
HttpMethod method = new HttpMethod("PATCH");
string requestUrl = $"https://graph.microsoft.com/v1.0/users/{UPN}?api-version=1.6";
var request = new HttpRequestMessage(method, requestUrl)
{
Content = new StringContent($"{payloadJSON}", Encoding.UTF8, "application/json")
};
var response = await client.SendAsync(request);
Console.WriteLine("Response: " + response);
if (!response.IsSuccessStatusCode)
{
throw new InvalidOperationException(response.ReasonPhrase);
}
}
According to 400 Bad Request, we could know that there is something wrong with http request. In your case, you could use Fiddler to catch the htt prequest, we could get Query parameter api-version not allowed. So you could remove the api version from the requesturl.
We could get more information about update use from Graph Update user API
PATCH /users/{id | userPrincipalName}
We also need to add the Authorization in the request header.
string requestUrl = $"https://graph.microsoft.com/v1.0/users/{UPN}";
var token ="Bearer eyJ0eXAiOiJKV1QiLCJub25jZSI6IkFRQUJBQUFBQUFCSGg0...."
...
request.Headers.Add("Authorization", token);
var response = await client.SendAsync(request);

Asp.net Web Api 2 - how to get access_token from C# code

I am preparing a C# Api for my website. When I call the following code to login and get the access token, response.IsSuccessStatusCode is ok (200), but I could not find any access_token from the response. I assume the access token comes through response body, but could not find a proper function to get the response body.
var token = new Dictionary<string, string> { {"grant_type", "password"}, {"username", "administrator#parkatstreet.com"},
{"password", "OOKKUUc564$"},};
var tknModel = new FormUrlEncodedContent(token);
var resp = await client.PostAsync("http://parkatstreet.com/Token", tknModel);
if (response.IsSuccessStatusCode)
{
string responseStream = response.Headers.ToString();
}
The response I am getting is:
{StatusCode: 200, ReasonPhrase: 'OK', Version: 1.1, Content:
System.Net.Http.StreamContent, Headers: { Pragma: no-cache
X-SourceFiles:
=?UTF-8?B?QzpcRGV2ZWxvcG1lbnRcUGF5cm9sbEFwaVxEYml0UGF5cm9sbEFwaVxEYml0UGF5cm9sbEFwaVxUb2tlbg==?=
Cache-Control: no-cache Date: Thu, 24 Sep 2015 05:19:10 GMT
Set-Cookie:
.AspNet.Cookies=lgQKnoQzwpUbpE9PpVm9L71rlBEBwG_oA4VT89oowNoynkdpHRfGj6Lt92XJ5N1Pnmfv_FUQ07EVuLOLpjiuLtnoqOE2SqAFvXr7tMQmoXlU-pvf8KwkTx6Fl_TyC-VrCPOoOcxEAolBcN3oHXHYcjYPaqmZpQA-mQqcjwxIumXd6eVEHfEZtRj3EiVLS0schzD9TG8IcPq3JkzEQpqu_srEBKbJQ8zIJX6TCfkFK3cvGGJ-6cbV8lIJcPke8ahnc_icDkPKnlfzZZEEZEzeamYX3u1g1R50bj-y01T0JXQLyqGK-EpzjiLwqeO5yv1-yJ_1GQrqv46lomu51WTY_oMIXvGTNEU8wurJtN2XdpBLKg1X79VQxqunniKpYGtYN1wq-sl-RPiFLz9Cnh21yD1ogSNJoWEutyOP3lpCvZp50cAktDqB-swG92_a8f6OPzFHSG0yUq01Ro1YFJNBljP5eWT8r9wGqP1ZlDHLAmQ;
path=/; HttpOnly Server: Microsoft-IIS/10.0 X-Powered-By: ASP.NET
Content-Length: 688 Content-Type: application/json; charset=UTF-8
Expires: -1 }}
And the response I expect is:
{
"access_token": "4b-KAhg7QNMyHNVXFBUFBq5NJvlw7_JmaXZl1SDLIi6sMl5kTh8EfnvNTNa5iUwQuiNSk2Il6nUxheAJ64rroYYF-woWcQ9l8J8g56IuCApUNJWzD31eyJrOBI2yzZcTFY8X0GqpidYhZNvTHsn4PNwOZAHAebBK64yMstb9-66kdgp-vSgvCvH1tA45drlWVuNsjmsX6EHg5WlDFJsPhnDL7Lz4sSYxtFF8ipZvAEoxJ-dGsQHRsIAygY934nrLdYP7saDCAAqlzvUoWspYIO2B9kyyzoYREjb3Y9ik8MEmuGZgk-hzAWkTRMh51tUn0wknMPVsDve_OYdX9qZlMoxDEXJjGhPmxMKd_o2AdGkPU31OTW6Y3JkQZVdTTHqUuCWMTWctkImvIpSRlpwfc71qRltbp1wy7SjHQdpeYC8ZBcjO-B6NImkxjM_yb2BVKM8TrXeqdYrRcKBer6RjpgMCwlha9oH8_yyFNqbw-U1YcrKLvIfJPqjJ45K37bkn",
"token_type": "bearer",
"expires_in": 1209599,
"userName": "administrator#parkatstreet.com",
".issued": "Thu, 24 Sep 2015 04:45:59 GMT",
".expires": "Thu, 08 Oct 2015 04:45:59 GMT" }
You can create a new Console Application and use the following code:
namespace APIClientConsole
{
class Program
{
static void Main(string[] args)
{
RunAsync().Wait();
}
static async Task RunAsync()
{
using (var client = new HttpClient())
{
// TODO - Send HTTP requests
client.BaseAddress = new Uri("http://localhost:24780/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// HTTP POST
var body = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("grant_type", "password"),
new KeyValuePair<string, string>("username", "bnk"),
new KeyValuePair<string, string>("password", "bnk123")
};
var content = new FormUrlEncodedContent(body);
HttpResponseMessage response = await client.PostAsync("token", content);
if (response.IsSuccessStatusCode)
{
string responseStream = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseStream);
Console.ReadLine();
}
}
}
}
}
You can read more at the following link
Calling a Web API From a .NET Client in ASP.NET Web API 2 (C#)
In your comment you use javascript to access to response content (or body as you call it)
$.post(url, data).success(saveAccessToken).always(showResponse);
In C# you access can get the content with
string responseStream = await response.Content.ReadAsStringAsync();
If you have Microsoft.AspNet.WebApi.Client referenced you can parse the content with
ResponseType result = await response.Content.ReadAsAsync<ResponseType>();

Categories