http-get - 如何在 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");
}
}
}
解决方案
好的,我可以看到一些问题。
在服务器上:
[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 无效。所以跳过那个。
推荐阅读
- python - 如何在 Python 中显示 Google 人脸检测 Vision API 使用的图像
- python - 如何在 Python 中制作经过验证的符号?
- python - Python:枚举txt文件中的行,后跟逗号
- c++ - C ++:char数组在发送期间丢弃一些值
- wordpress - Wordpress elementor 阻止了具有来源的框架访问跨域框架
- css - 如何将 bootsrap 5 navbar li 元素向右移动
- javascript - 如何使用带有过滤器的字符串数组的 for 循环?
- c# - 你如何处理 git 中的临时 nuget 包更新
- tensorflow - 来自自定义函数的 IoU 得分与来自 Keras 指标的平均 IoU 不匹配
- javascript - Node.js:如何透明地要求和导出子模块