Search code examples
http-getblazor-webassemblywebapijsonserializer

How to covert Json result into string in Blazor WebAssembly?


I want to convert the result into a string and pass it to the navigation path, but I couldn't do it, please help me.

HttpGet Controller

[HttpGet]
[Route("UserId")]
public async Task<ActionResult<ApplicationUser>> GetUserId(string Username)
{
  var user = await userManager.FindByNameAsync(Username);
  if (user == null)
  return StatusCode(StatusCodes.Status500InternalServerError, new Response { Status = "Error", Message = "User not exist" });
  var result = await userManager.GetUserIdAsync(user);
  return new JsonResult(result);
}

Controller return result

"85e39a3e-8101-4166-9193-5e41bec1a7ce"

Function

private async Task Login()
    {
        var user = new userName { Username = Username };
        var loginUser = new LoginDb { Username = Username, Password = Password };
        if (Username == null || Password == null)
        {
            toastService.ShowWarning("Please enter Username and Password");
        }
        else
        {
            user = await Http.GetFromJsonAsync<userName>("Authentication/UserId?Username=" + Username);
            if (user != null)
            {
                string Id = System.Text.Json.JsonSerializer.Serialize(user);
                var result = await Http.PostAsJsonAsync("Authentication/login", loginUser);
                if (result.IsSuccessStatusCode)
                {
                    NavigationManager.NavigateTo("/profile/" + Id);
                    toastService.ShowSuccess("Login successful");
                }
                else
                {
                    toastService.ShowError("Username or Password is wrong");
                }
            }
            else
            {
                NavigationManager.NavigateTo("/login");
            }

        }
    }

Solution

  • OK, I can see a few problems.

    On the Server:

    [HttpGet]
    [Route("UserId")]
    public async Task<ActionResult<ApplicationUser>> GetUserId(string Username)   // A
    {
      var user = await userManager.FindByNameAsync(Username);
      if (user == null) // B
      return StatusCode(StatusCodes.Status500InternalServerError, new Response { Status = "Error", Message = "User not exist" });
      var result = await userManager.GetUserIdAsync(user);
      return new JsonResult(result);
    }
    

    First, your return type here is Task<ActionResult<ApplicationUser>> . ApplicationUser is tied to the backend Identity library, you can't and shouldn't use it for a DTO.

    And you don't, in the end you have return new JsonResult(result); which is OK when you change the return type to just Task<ActionResult>.

    On the client:

    //user = await Http.GetFromJsonAsync<userName>("Authentication/UserId?Username=" + Username);
      var userId = await Http.GetFromJsonAsync<string>("Authentication/UserId?Username=" + Username);
    

    The endpoint returns a simple string. Json does not know about 'UserName' or anything else.

    //string Id = System.Text.Json.JsonSerializer.Serialize(user); -- use UserId
    

    You are serializing the Id (again) here, making it almost certainly invalid for an URL. So just skip that.