首页 > 解决方案 > 使用值从 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);
        });
    }
}

警报永远不会被调用,我不知道它是否在做任何事情。当我按下提交按钮时,表单会清除,仅此而已。

标签: reactjsasp.net-core

解决方案


在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();
}

参考这个


推荐阅读