首页 > 解决方案 > 如何在 Blazor WebAssembly 中将 Json 结果转换为字符串?

问题描述

我想将结果转换为字符串并将其传递给导航路径,但我做不到,请帮助我。

HttpGet 控制器

[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);
}

控制器返回结果

“85e39a3e-8101-4166-9193-5e41bec1a7ce”

功能

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");
            }

        }
    }

标签: http-getblazor-webassemblywebapijsonserializer

解决方案


好的,我可以看到一些问题。

在服务器上:

[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);
}

首先,您的返回类型是Task<ActionResult<ApplicationUser>>. ApplicationUser 与后端身份库绑定,您不能也不应该将其用于 DTO。

而你没有,最终return new JsonResult(result);当你将返回类型更改为 just 时你就可以了Task<ActionResult>

在客户端:

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

端点返回一个简单的字符串。Json 不知道“用户名”或其他任何内容。

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

您在此处(再次)序列化 Id,几乎可以肯定它对 URL 无效。所以跳过那个。


推荐阅读