I need your help guys. I'm developing a front-end with Blazor which sends request to ASP.Net Core.
I have the following code which gets an API response, in this case it returns the entire body of the response. What I'm trying to get here is the status code of the response only, example (200).
await Http.SendJsonAsync(HttpMethod.Post, "https://da3.mock.pstmn.io/api/register", CurrentUser);
var response = await Http.GetStringAsync("/api/register");
Console.WriteLine(response);
Use the other GetAsync method.
//var response = await Http.GetStringAsync("/api/register");
//Console.WriteLine(response);
var response = await Http.GetAsync("/api/register");
Console.WriteLine(response.StatusCode); // also see response.IsSuccessStatusCode
For POST method you could use SendAsync, you need to use PMC to install Newtonsoft.Json package firstly:
var requestMessage = new HttpRequestMessage()
{
Method = new HttpMethod("POST"),
RequestUri = new Uri("https://localhost:5001/api/default"),
Content = new StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(CurrentUser))
};
requestMessage.Content.Headers.ContentType =
new System.Net.Http.Headers.MediaTypeHeaderValue(
"application/json");
var result = await Http.SendAsync(requestMessage);
var responseStatusCode = result.StatusCode;
For GET method,what Henk Holterman has suggested (use Http.GetAsync) works well.
Refer to
https://learn.microsoft.com/en-us/aspnet/core/blazor/call-web-api?view=aspnetcore-3.0#httpclient-and-httprequestmessage-with-fetch-api-request-options
Related
I am new to flutter and I am using mongodb to save the credentials from signup page. When tried to give credentials that already exists server shows a response - 'user already exits' this response was viewed in postman. I am able to get statusCode but I am unable to get the same response in flutter. below is my flutter code.
Future<String> uploadImage(filename) async {
var request = http.MultipartRequest('POST', Uri.parse(serverReceiverPath));
request.files.add(await http.MultipartFile.fromPath('file', filename));
var res = await request.send();
print(res.statusCode);
return null;
}
To get the body response, use res.stream.bytesToString()
Complete code:
Future<String> uploadImage(filename) async {
var request = http.MultipartRequest('POST', Uri.parse(serverReceiverPath));
request.files.add(await http.MultipartFile.fromPath('file', filename));
var res = await request.send();
print(res.statusCode); // status code
var bodyResponse = await res.stream.bytesToString(); // response body
print(bodyResponse);
return null;
}
Can you point me to the right way and set of parameters to:
Make an authorization request with PKCE to my identity endpoint (https://.../login) in Postman
In the attachments there is the list of parameters that send.
as grant_type value I use --> authorization_code
Unfortunately I get "bad request", Invalid_grant in Postman
make the access token request. In this request I get Invalid request. I guess I miss the parameter refresh token but I don't know how to get/generate it:
I wrote the code of the Azure function to request the Access Token, unfortunately I get {"error":"invalid_request"} from the token endpoint.
Here is my code, can you tell me what I am doing wrong?
[FunctionName("GetAccessToken")]
public async Task<IActionResult> GetAccessToken(
[HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequest req,
ILogger log)
{
try
{
log.LogInformation("C# HTTP trigger function ''GetAccessToken'' processed a request.");
string clientSecret = "some secret";
string accessToken = "";
RequestAccessToken rT = new RequestAccessToken();
rT.Code = req.Form["code"];
rT.RedirectUri = req.Form["redirect_uri"];
rT.GrantType = req.Form["grant_type"];
rT.ClientId = req.Form["client_id"];
rT.CodeVerifier = req.Form["code_verifier"];
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("https://<access_token_endpoint_base_uri>");
client.DefaultRequestHeaders
.Accept
.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"));//ACCEPT header
var body = new { EntityState = new {
code = rT.Code,
redirect_uri = rT.RedirectUri,
grant_type = rT.GrantType,
client_id = rT.ClientId,
client_secret = clientSecret,
code_verifier = rT.CodeVerifier
} };
var result = await client.PostAsJsonAsync(
"/login",
body);
accessToken = await result.Content.ReadAsStringAsync();
}
return new OkObjectResult(accessToken);
}
catch (Exception ex)
{
log.LogInformation(ex.ToString());
return new ObjectResult(ex.ToString()) { StatusCode = 500 };
}
}
Steps 4 and 8 of my blog post show the standard PKCE parameters.
It is tricky to reproduce the whole flow via a tool such as Postman though, since there is typically also the need to follow redirects and manage a form post of user + password.
I am trying to figure out how to implement a delegation grant type in conjunction with client credentials, by following the tutorial from HERE, which is literally one page, since I have and API1 resource calling another API2 resource.
I've implemented the IExtensionGrantValidator and copied the code from the docs using the class name they provided, and added the client with grant type delegation. However, I am not sure where and how to call this method below, at first I was calling it from the client and tried passing the JWT I initially got to call API1 to the DelegateAsync method but I kept getting a bad request
In API 1 you can now construct the HTTP payload yourself, or use the IdentityModel helper library:
public async Task<TokenResponse> DelegateAsync(string userToken)
{
var payload = new
{
token = userToken
};
// create token client
var client = new TokenClient(disco.TokenEndpoint, "api1.client", "secret");
// send custom grant to token endpoint, return response
return await client.RequestCustomGrantAsync("delegation", "api2", payload);
}
So, I tried from API1 requesting a token in a method called GetAPI2Response which attempts to call a method in API2:
[HttpGet]
[Route("getapi2response")]
public async Task<string> GetApi2Response()
{
var client = new HttpClient();
var tokenResponse = await client.RequestTokenAsync(new TokenRequest
{
Address = "http://localhost:5005/connect/token",
GrantType = "delegation",
ClientId = "api1_client",
ClientSecret = "74c4148e-70f4-4fd9-b444-03002b177937",
Parameters = { { "scope", "stateapi" } }
});
var apiClient = new HttpClient();
apiClient.SetBearerToken(tokenResponse.AccessToken);
var response = await apiClient.GetAsync("http://localhost:6050/api/values");
if (!response.IsSuccessStatusCode)
{
Debug.WriteLine(response.StatusCode);
}
else
{
var content = await response.Content.ReadAsStringAsync();
return content;
}
return "failed";
}
However, this returns when debugging an invalid grant type. Strangely, I noticed when running IDSRV the code in the IExtensionGrantValidator method does not get hit, until you click the link for the discovery docs then it appears as a grant type
I'm obviously doing something wrong since I am not including the aforementioned DelegateAsync method from the docs, as its not clear to me where it goes.
The docs seem to be a bit outdated. With the actual extension methods there must be something like:
var tokenResponse = await client.RequestTokenAsync(new TokenRequest
{
Address = "http://localhost:5005/connect/token",
GrantType = "delegation",
ClientId = "api1_client",
ClientSecret = "74c4148e-70f4-4fd9-b444-03002b177937",
Parameters = new Dictionary<string, string>{{ "token", userToken }, { "scope", "stateapi" } }
})
you already implemented it, but forgot to add the initial token. When you extract it from the GetApi2Response() it can become your DelegateAsync.
Then your client configuration in Identityserver has to contain the delegation GrantType for the api1_client. Also don't forget the registration:
services.AddIdentityServer().AddExtensionGrantValidator<YourIExtensionGrantValidatorImpl>()
I have a Aspnet Core API thats trying to connect to a Microsoft Dynamics 365 instance. The goal is to push data to the CRM Instance using an API.
In order to do this, I have a CRM User and a Pass and my understanding is I will need an OAuth token to actually complete my request.
How can I go about getting that OAuth token from an API ?
My current (non working) code looks like this:
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(CrmFInanceCCNotifyDto.Instance.CrmBaseUri);
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(
"Basic", Convert.ToBase64String(Encoding.ASCII.GetBytes($"{CrmFInanceCCNotifyDto.Instance.CrmUser}:" +
$"{CrmFInanceCCNotifyDto.Instance.CrmPass}")));
client.DefaultRequestHeaders.Add("OData-MaxVersion", "4.0");
client.DefaultRequestHeaders.Add("OData-Version", "4.0");
client.DefaultRequestHeaders.Add("Accept", "application/json");
client.DefaultRequestHeaders.Add("If-Match", "*");
var method = "PATCH";
var httpVerb = new HttpMethod(method);
string path = client.BaseAddress + CrmFInanceCCNotifyDto.Instance.CrmLocationUpdateUri;
string jsonPayload = "{\"entity.dfnd_financingused\": 1}";
var stringContent = new StringContent(jsonPayload, Encoding.UTF8, "application/json");
var httpRequestMessage =
new HttpRequestMessage(httpVerb, path)
{
Content = stringContent
};
try
{
var response = await client.SendAsync(httpRequestMessage);
Any pointers in solving this will be much appreciated.
Thanks
I have REST API that returns if user exists or not by email.
If user exists and I am getting back status OK from API all works fine, but when API response with 404 my app crash. I can't figure out how to check if status is ok or not before app crash and redirect user to register page in case user is not found by API.
Here is code that makes request to api:
string getuserUrl = $"https://localhost:99282/api/users/{email}";
var client = new HttpClient();
var uri = new Uri(getuserUrl);
var result = await client.GetStringAsync(uri);
var userResult = JsonConvert.DeserializeObject<User>(result);
return userResult;
You can use below code to identify whether the API call is success or not.
String URL = "https://localhost:99282/api/users/{email}";
using (HttpClient client = new HttpClient())
{
client.BaseAddress = new Uri(URL);
try
{
HttpResponseMessage response = await client.GetAsync(URL);
if (response.IsSuccessStatusCode)
{
// Code 200 - If the API call is sucess
// You redirect to another page
}
else
{
// Show alert for failed calls
}
}
catch (Exception ex)
{
return null;
}
}