skip to Main Content

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

image show data I need to receive

How to deserialize data from var response to get details data as
message,status,userid and username and user role and environment ?

2

Answers


  1. var jsonResponse = await response.Content.ReadAsStringAsync();
    

    Above line will give json string. In your case like below :

        {
            "message": "success",
            "status": true,
            "data": {
                "userID": "9595",
                "userName": "ADC Test User",
                "userRole": "Administrator",
                "environment": "PY"
            },
            "statusCode": "0000"
        }
    

    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)

        public class UserAuthResponse 
        {
           [JsonPropertyName("message")]
           public string Message { get; set; };
           [JsonPropertyName("status")]
           public string Status { get; set; }; 
           [JsonPropertyName("data")]
           public UserData Data { get; set; };
           [JsonPropertyName("statusCode")]
           public int StatusCode { get; set; };
        }
        
        public class UserData
        {
           [JsonPropertyName("userID")]
           public long UserID { get; set; }; 
           [JsonPropertyName("userName")]
           public string UserName { get; set; };
           [JsonPropertyName("userRole")]
           public string UserRole { get; set; };
           [JsonPropertyName("environment")]
           public string Environment { get; set; };
        }
    

    For deserialization you can do

        UserAuthResponse? userAuthResponse = 
                        JsonSerializer.Deserialize(jsonResponse);
    

    Then after you can do

        if(userAuthResponse is not null)
        {
          if(userAuthResponse.Message == "success" && userAuthResponse.Status)
          {
            .....
          }
        }
    

    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

    Login or Signup to reply.
  2. You can try the follwoing code.

        [Route("api/[controller]")]
        [ApiController]
        public class adcxx : ControllerBase
        {
            private readonly HttpClient _httpClient;
    
            public adcxx(HttpClient httpClient)
            {
                this._httpClient = httpClient;
            }
    
            [HttpGet("ValidateUser")]
            public IActionResult ValidateUser()
            {
                return new JsonResult(new { message = 1, status = true, data = new {userID=9595,userName= "ADC Test User",userRole= "Administrator", environment="PY" },statusCode=0000 }); 
            }
    
            [HttpGet("test")]
            public async Task OnPost()
            {
    
                HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, "https://localhost:7215/api/adcxx/ValidateUser");
                var response = await _httpClient.SendAsync(request);
                if (response.IsSuccessStatusCode)
                {
                    var jsonResponse = await response.Content.ReadAsStringAsync();            
                    var jobject = JObject.Parse(jsonResponse);
    
                    var message = jobject["message"];
                    var status = jobject["status"];
                    var userID = jobject["data"]["userID"];
                    var userName = jobject["data"]["userName"];
                    var userRole = jobject["data"]["userRole"];
                    var environment = jobject["data"]["environment"];
                    var statusCode = jobject["statusCode"];
    
                    Console.WriteLine(jobject);
                    Console.WriteLine(message);
                    Console.WriteLine(status);
                    Console.WriteLine(userID);
                    Console.WriteLine(userName);
                    Console.WriteLine(userRole);
                    Console.WriteLine(environment);
                    Console.WriteLine(statusCode);
                }
            }
        }
    

    Test output from /api/adcxx/test
    enter image description here

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search