我有一个Web API POST请求,该请求应该使用在主体中找到的属性作为JSON向特定表添加一个新记录。然而,当输入所有的属性(我认为这是正确的)时,请求最终将添加一个新的记录,然而所有的属性将被设置为空,无论出于什么原因?
以下是我的API Post请求:
/*Define URL endpoint for adding a single role*/
[System.Web.Http.Route("api/Roles/addRole")]
/*HttpPost header, ensures only the usage of POST requests*/
[System.Web.Mvc.HttpPost]
/*Main return new list with added role*/
public List<dynamic> addRole([FromBody] Roles roles)
{
if (roles != null)
{
/*Create an instance of the UltimateDB*/
UltimateDBEntities db = new UltimateDBEntities();
/*Optimize memory usage by disabling proxy creation*/
db.Configuration.ProxyCreationEnabled = false;
db.Roles.Add(roles);
db.SaveChanges();
return getAllRoles();
}
else
{
return null;
}
}
上面应该使用用户输入的来自正文(JSON)的数据向“roles”表添加一条记录。我使用Postman对此进行了测试,返回的只是一个新记录,其所有属性都设置为NULL。
例如,我将输入以下内容:
{
"Name": "Lab Employee",
"Description": "User only has read rights",
"Tenant_rental": 1,
"Property_Module": 0,
"Employee_Management": 0,
"Reports": 1,
"administration": 1,
"user_Password_access": 0,
"Building_Management": 0,
"Credit_Bureau": 1
}
把这个作为我的新唱片:
{
"ID": 23,
"Name": null,
"Description": null,
"Tenant_rental": null,
"Property_Module": null,
"Employee_Management": null,
"Reports": null,
"administration": null,
"user_Password_access": null,
"Building_Management": null,
"Credit_Bureau": null
}
我的角色类:
namespace U18043039_HW1.Models
{
using System;
using System.Collections.Generic;
public partial class Roles
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public Roles()
{
this.User_Table = new HashSet<User_Table>();
}
public int Role_ID { get; set; }
public string Role_Name { get; set; }
public string Role_Description { get; set; }
public Nullable<bool> Role_Tenant_rental { get; set; }
public Nullable<bool> Role_Property_Module { get; set; }
public Nullable<bool> Role_Employee_Management { get; set; }
public Nullable<bool> Role_Reports { get; set; }
public Nullable<bool> Role_administration { get; set; }
public Nullable<bool> Role_user_Password_access { get; set; }
public Nullable<bool> Role_Building_Management { get; set; }
public Nullable<bool> Role_Credit_Bureau { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<User_Table> User_Table { get; set; }
}
}
使用此数据进行测试:
{
"Role_Name": "Lab Employee",
"Role_Description": "User only has read rights",
"Role_Tenant_rental": True,
"Role_Property_Module":False,
... and so on
}