c# - put 方法的参数值为 null

标签 c# asp.net-core

这是模型:

using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Text;

namespace CollectionsCatalogWebAPI.Models
{
    [Table("User")]
    public class User
    {

        #region attributes

        private Int64 id;
        private String username;
        private String firstName;
        private String middleInitials;
        private String lastName;
        private String password;
        private String gender;
        private String active;

        #endregion

        #region properties

        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public Int64 Id
        {
            set { this.id = value; }
            get { return this.id; }

        }

        [StringLength(50)]
        public String Username
        {
            set { this.username = value; }
            get { return this.username; }
        }

        [StringLength(50)]
        public String FirstName
        {
            set { this.firstName = value; }
            get { return this.firstName; }
        }

        [StringLength(10)]
        public String MiddleInitials
        {
            set { this.middleInitials = value; }
            get { return this.middleInitials; }
        }

        [StringLength(50)]
        public String LastName
        {
            set { this.lastName = value; }
            get { return this.lastName; }
        }

        [StringLength(64)]
        public String Password
        {
            set { this.password = value; }
            get { return this.password; }
        }

        [StringLength(1)]
        public String Gender
        {
            set { this.gender = value; }
            get { return this.gender; }
        }

        [StringLength(1)]
        public String Active
        {
            set { this.active = value; }
            get { return this.active; }
        }

        #endregion

        #region especifcMethods

        /// <summary>
        /// Returns a string representation of this instance.
        /// </summary>
        /// <returns>Returns a string representation of this instance.</returns>
        public override String ToString()
        {
            StringBuilder sb = new StringBuilder();

            sb.Append("[CollectionsCatalogWebAPI.Models.User:");
            sb.Append(" Username: ");
            sb.Append(this.Username);
            sb.Append(" FirstName: ");
            sb.Append(this.FirstName);
            sb.Append(" MiddleInitials: ");
            sb.Append(String.IsNullOrEmpty(this.MiddleInitials) ? "" : this.MiddleInitials);
            sb.Append(" LastName: ");
            sb.Append(String.IsNullOrEmpty(this.LastName) ? "" : this.LastName);
            sb.Append(" Gender: ");
            sb.Append(String.IsNullOrEmpty(this.Gender) ? "" : this.Gender);
            sb.Append(" Active: ");
            sb.Append(String.IsNullOrEmpty(this.Active) ? "" : this.Active);
            sb.Append("]");

            return sb.ToString();
        }

        #endregion
    }
}

现在在 Controller 上,两种方法 GET 都可以,但是 POST 不起作用。

using System;
using System.Collections.Generic;
using System.Linq;
using CollectionsCatalogWebAPI.Config;
using CollectionsCatalogWebAPI.Models;
using Microsoft.AspNetCore.Mvc;

namespace CollectionsCatalogWebAPI.Controllers
{
    [Produces("application/json")]
    [Route("api/Users")]
    public class UsersController : Controller
    {

        private readonly CollectionsCatalogContex context;

        public UsersController(CollectionsCatalogContex context)
        {
            this.context = context;
        }

        [HttpGet]
        public IEnumerable<User> Get()
        {
            return context.UsersModel.ToList<User>();
        }

        [HttpGet("{id}", Name = "Get")]
        [ProducesResponseType(200, Type = typeof(User))]
        [ProducesResponseType(404)]
        public IActionResult Get(Int64 id)
        {
            var user = context.UsersModel.Find(id);

            if (user == null)
            {
                return NotFound();
            }

            return Ok(user);
        }

        // POST: api/Users
        [HttpPost]
        public IActionResult Post(User u)
        {
            context.UsersModel.Add(u);
            context.SaveChanges();

            return CreatedAtRoute("Get", new { id = u.Id}, u);
        }
    }
}

当我使用 Postman 发布下面的 json 时,我收到一条 SQL 错误,提示“事件字段不能为空”。

{
    "Id":0,
    "Username":"TEST_POST",
    "FirstName":"POSTADO",
    "MiddleInitials":"API",
    "LastName":"PELO POSTMAN",
    "Password":"senha123",
    "Gender":"M",
    "Active":"N"
}

(没有Id信息返回同样的错误)

但是在调试时我看到参数 User (u) 为空。

我可以在 ToString 上看到它:

u   {[CollectionsCatalogWebAPI.Models.User: Username:  FirstName:  MiddleInitials:  LastName:  Gender:  Active: ]}

关于这个的一些提示?

最佳答案

您必须像这样使用[FromBody]:

public IActionResult Post([FromBody]User u)

通过这种方式,您可以将请求主体中的数据绑定(bind)到 User 对象

关于c# - put 方法的参数值为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51330694/

相关文章:

c# - INotifyPropertyChanged:线程安全 Dispatcher 实现的风险

c# - 将 Angular 应用程序分解为多个 Visual Studio 项目的方法

php - 当 Firefox 显示 "the Image cannot be displayed because it contains errors"时,我如何找出错误是什么?

asp.net - 如何在 ASP.NET vNext MVC 6 (beta1) 项目之间共享 View ?

jenkins - 如何在 Docker 中运行 .Net 项目作为 jenkins 作业的一部分

c# - 如何在#if 语句中设置.NET Core 进行编译

c# - 使用 Linq 更新列表

c# - (手动)序列化和反序列化二叉搜索树

c# - Python 是一种托管代码语言吗?

c# - 将 SQL 子查询转换为 In to Linq Lambda