【问题标题】:POST parameter is null in when it's a hand made type当它是手工类型时,POST 参数为空
【发布时间】:2019-08-08 13:48:52
【问题描述】:

我有一个 asp.net 4.5.2 web api,一个 POST 方法接收我手动编码的 DTO 参数,如下所示:

using System;

namespace WebApi.Models.DTO
{
    [Serializable]
    public class MyModelDto
    {
        public MyModelDto()
        {

        }

        public int Id { get; set; }
        public string Code { get; set; }
        public int Type { get; set; }
    }
}

当我从 Postman 调用此方法时,参数始终为 null,但如果我在 EntityFramewok(edmx 模型)中设计相同的 DTO 类并将其用作参数,我可以在发送时在 post 方法中接收数据。 我无法意识到我在手工课上缺少什么? 为什么它使用 EF 而不是我的班级? 将参数设置为动态也可以...

[HttpPost]
[JwtAuthentication]
[Route("api/bills/invoice")]
public JsonResult<WebApi.Models.DTO.MyModelDto> Post(WebApi.Models.DTO.MyModelDto param)
{
    // Here param is always NULL
}

[HttpPost]
[JwtAuthentication]
[Route("api/bills/invoice")]
public JsonResult<Data.MyModelDto> Post(Data.MyModelDto param)
{
    // Here param wors! based on the EF class
}
public JsonResult<Data.MyModelDto> Post(dynamic param)
{
    // Here param wors! using dynamic data type
}

【问题讨论】:

  • 无论哪种方式都应该工作,POST确实与模型没有任何关系。当您从 Postman 发送参数时,您是如何做到的?只是一个猜测,但可能模型的序列化方式不同:大写与驼峰式。
  • 你给出的例子应该有效。您可能需要粘贴不工作的确切 DTO 对象。 #null 值将在模型绑定器无法将 JS 对象隐式转换为 Post 参数时。 AFAIK 活页夹不区分大小写,但请仔细检查 DTO 属性的命名。有时会出现拼写错误。

标签: entity-framework asp.net-web-api dto edmx


【解决方案1】:

这取决于您如何通过 Postman 发送数据。

我这里没有 Postman 来测试,但请确保您在发送数据时选择 Json 类型,然后您发送的数据需要与您的 DTO 匹配。比如:

{
   "Id":1,
   "Type":"whatever",
   "Code":"whatever"
}

自从您发送 Post 请求以来,此数据将进入请求正文。

一个额外的观察,你的 DTO 不需要一个空的构造函数,你可以摆脱它。没有错:

public class MyModelDto
    {       
        public int Id { get; set; }
        public string Code { get; set; }
        public int Type { get; set; }
    }

出于测试目的,请摆脱您的 Jwt 身份验证,直到您的调用正常运行

【讨论】:

    猜你喜欢
    • 2012-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-30
    • 1970-01-01
    • 2015-07-04
    • 2016-09-19
    • 1970-01-01
    相关资源
    最近更新 更多