首页 > 解决方案 > 将数据发布到控制器 .net 核心

问题描述

我有以下控制器:

[Route("api/[controller]")]
[Authorize]
public class AuthenticationController : Controller
{
    private readonly IAuthenticationService _authenticationService;

    public AuthenticationController(IAuthenticationService authenticationService)
    {
        _authenticationService = authenticationService;
    }

    [AllowAnonymous]
    [HttpPost]
    public IActionResult Authenticate([FromBody] UserModel userParams)
    {
        var authenticate = _authenticationService.Authenticate(userParams.Username, userParams.Password);
        return Ok("");
    }

    [HttpGet]
    public IActionResult GetAll()
    {
        var users = "Greta";
        return null;
    }
}

我正在尝试与邮递员一起发帖,但我得到了这个结果:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title>Error</title>
    </head>
    <body>
        <pre>Cannot POST /api/Authentication/Authenticate</pre>
    </body>
</html>

在此处输入图像描述

有人知道我为什么会收到此错误吗?

我将 React 模板与 Visual Studio 一起使用。可能与此有关吗?

当我尝试访问 GetAll 端点时,我得到了这个:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
        <meta name="theme-color" content="#000000">
        <base href="/" />
        <!--
      manifest.json provides metadata used when your web app is added to the
      homescreen on Android. See https://developers.google.com/web/fundamentals/engage-and-retain/web-app-manifest/
    -->
        <link rel="manifest" href="/manifest.json">
        <link rel="shortcut icon" href="/favicon.ico">
        <!--
      Notice the use of  in the tags above.
      It will be replaced with the URL of the `public` folder during the build.
      Only files inside the `public` folder can be referenced from the HTML.

      Unlike "/favicon.ico" or "favicon.ico", "/favicon.ico" will
      work correctly both with client-side routing and a non-root public URL.
      Learn how to configure a non-root public URL by running `npm run build`.
    -->
        <title>ICOM.Cbs</title>
    </head>
    <body>
        <noscript>
      You need to enable JavaScript to run this app.
    </noscript>
        <div id="root"></div>
        <!--
      This HTML file is a template.
      If you open it directly in the browser, you will see an empty page.

      You can add webfonts, meta tags, or analytics to this file.
      The build step will place the bundled scripts into the <body> tag.

      To begin the development, run `npm start` or `yarn start`.
      To create a production bundle, use `npm run build` or `yarn build`.
    -->
        <script type="text/javascript" src="/static/js/bundle.js"></script>
    </body>
</html>

编辑:它现在似乎工作了。我删除了 FromBody 然后它起作用了。我也尝试过使用 FromForm,它可以工作。我不知道为什么。

标签: c#.net-core

解决方案


[FromBody]仅在您的控制器中使用并且您正在使用 PostMan 进行测试时。而不是使用form-data使用raw并选择首选Content-Type: application/json

在此处输入图像描述


推荐阅读