I work on asp.net razor page Login user name and password . I call Web API validate user
name and password . my issue I face I can’t deserialize data response returned after login success
JSON data returned from web API after success login username and password
{
"message": "success",
"status": true,
"data": {
"userID": "9595",
"userName": "ADC Test User",
"userRole": "Administrator",
"environment": "PY"
},
"statusCode": "0000"
}
I call API from razor page login as below :
public async Task OnPost()
{
UserLoginViewModel loginview = new UserLoginViewModel();
loginview.UserID = User.UserName;
loginview.Password = User.vPassword;
var json = JsonSerializer.Serialize(loginview);
var content = new StringContent(json, Encoding.UTF8, "application/json");
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "https://localhost:44374/api/adcxx/ValidateUser");
request.Content = content;
var response = await _httpClient.SendAsync(request);
if (response.IsSuccessStatusCode)
{
}
}
I need to deserialize returned data from login success where message=success
as logic below :
if (response.IsSuccessStatusCode)
{
IF(message=="success" AND status="true")
{
receive `user id and username and user role and password`
}
}
image below explain what I need to do exactly
How to deserialize data from var response
to get details data as
message,status,userid and username and user role and environment ?
2
Answers
Above line will give json string. In your case like below :
Further you can desterilize this json in c# class, for that purpose create one class for example named UserAuthResponse like below (according to your response)
For deserialization you can do
Then after you can do
For further better understanding please read below official docs from MS
https://learn.microsoft.com/en-us/dotnet/fundamentals/networking/http/httpclient
https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json/how-to?pivots=dotnet-8-0
You can try the follwoing code.
Test output from /api/adcxx/test