【问题标题】:All variables are null at the request with Axios to ASP.Net Core Controller在 Axios 到 ASP.Net Core Controller 的请求中,所有变量都为空
【发布时间】:2018-01-27 01:18:58
【问题描述】:

这是我的客户请求代码:

import request from 'axios';

//...

     let url = 'Login/SignIn',
                headers = {
                    headers: {
                        'Content-Type': 'application/json'
                    }
                },
                data = JSON.stringify( {
                    name: 'danil',
                    password: 'pwd'
                });

     request.post(url, data, headers);

乍一看还不错。

请求在此处待处理:

但这一切都在我的控制器中结束了:

这是代码顺便说一句:

[HttpPost]
        public async Task<ActionResult> SignIn([FromBody]string name, [FromBody]string password)
        {

            var userLoginCommand = new UserLogInCommand {
                Login = name,
                Password = password
            };

            await _dispatcher.DispatchAsync(userLoginCommand);
            return Content(userLoginCommand.Result, "application/json");
        }

这有什么问题吗?我忘记了什么?

我尝试通过添加和删除JSON.stringify 来玩弄它,尝试不发送标头(然后它抛出415 error)但那里没有任何变化。仍然有空值。

UPD: 正如阿里在 cmets 中建议的那样,如果我们使用 LoginModel 来传递数据就可以了:

 public class LoginModel
        {
            public string name { get; set; }
            public string password { get; set; }
        }

但是为什么它不能以简单的方式那样工作呢?

【问题讨论】:

  • 您是否尝试过使用name 和password 属性创建类并像下面的Task&lt;ActionResult&gt; SignIn([FromBody]LoginModel model) 一样传递它?
  • 不,它也应该这样工作,不是吗? DTO 是一种选择,是的,但仍然
  • @Ali 创建了它,它的工作原理就是这样,但有模型
  • 请阅读从请求正文中绑定格式化数据Model Binding部分的第一条注释
  • 为什么不以简单的方式工作??

标签: javascript asp.net ajax asp.net-core axios


【解决方案1】:

只允许从消息体中读取一个参数。 在您的示例中,您有两个具有 FromBody 属性的参数,这就是您有空值的原因。

请在此处查找文档: https://docs.microsoft.com/en-us/aspnet/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api

"消息体最多允许读取一个参数。"

【讨论】:

    猜你喜欢
    • 2020-02-17
    • 2020-02-14
    • 2018-09-21
    • 2021-11-02
    • 1970-01-01
    • 2020-04-15
    • 2019-08-03
    • 2020-10-26
    相关资源
    最近更新 更多