reactjs - 使用值从 React 调用 .NET Core 控制器方法
问题描述
我是 React 的新手,我只是找不到关于如何在我的 .NET Core 应用程序中调用控制器、从表单输入向其发送值然后从中获取结果的明确信息。看起来这应该不难,但也许我知道得太少以至于我问谷歌错误的问题。反正...
我有一个看起来像这样的控制器方法。我从邮递员那里打电话给它,它似乎工作。
[ApiController]
[Route("user")]
public class UserController : ControllerBase
{
[HttpGet]
[Route("login/authenticate")]
public async Task<IActionResult> AuthenticateUserAsync([FromBody] AuthenticateUserRequest request)
{
... // sends request to back-end and gets a response
return Ok(response);
}
}
有一个看起来像这样的请求类,我希望在此处设置 React 表单中的 UserID 和 Password 属性。
public class AuthenticateUserRequest: Request
{
public string UserID { get; set; }
public string Password { get; set; }
}
返回的响应包含一个字符串列表,用于通过控制器中的身份对用户进行身份验证。我想将此列表返回给 React 以显示用户拥有的权限。
public class AuthenticateUserResponse: Response
{
public List<String> Permissions { get; set; }
}
我试图用这样的东西来调用它:我从这里得到了这个 fetch 示例:ASP.NET Core React 项目模板 - 如何链接到 C# 后端 ,但它似乎不起作用。
handleSubmit(event) {
if (this.state.userId == "" || this.state.password == "") {
alert('Please enter User ID and Password.');
event.preventDefault();
}
else {
fetch('user/login/authenticate', {
method: 'get',
headers: { 'Content-Type': 'application/json' },
body: {
"UserID": this.state.userId.value,
"Password": this.state.password.value
}
})
.then(response => response.json())
.then(data => {
alert(data);
});
}
}
警报永远不会被调用,我不知道它是否在做任何事情。当我按下提交按钮时,表单会清除,仅此而已。
解决方案
在ajax中使用get请求中的动作时Core API
,需要使用[FromQuery]
属性而不是[FromBody]属性来接受参数。
[HttpGet]
[Route("login/authenticate")]
public async Task<IActionResult> AuthenticateUserAsync([FromQuery] AuthenticateUserRequest request)
{
... // sends request to back-end and gets a response
return Ok();
}
参考这个。
推荐阅读
- ms-access - 从 Ms Access 2010 的报告中隐藏零值余额行
- ssl - 使用 tls_client_method 时使用的是什么 TLS/SSL 协议?
- laravel - laravel vapor schedule 作业未按计划运行
- neo4j - Neo4j 检查创建结果最佳实践
- python - 以一定的概率将 2 个值随机放入数组中
- python - imread - FileNotFoundError:没有这样的文件:
- linux - 查找在给定时间范围内修改的文件
- java - 评估 2 个输入变量值是否可以求和为一个输入值
- python-3.x - 不能用beautifulsoup 抓取谷歌搜索结果
- php - 我的 HTML 都没有显示在我的 PHP 页面上