[英]asp.net web api - post a object to web api
我正在尝试将用户对象从 ac# 客户端应用程序发布到应将新用户存储到数据库中的 web api。 该模型基于同一类。 目前客户端这个功能用于做帖子:
public static async Task CreateNewUser(string userName, string eMail, string password, string name, string firstName)
{
User newUser = new User(userName, eMail, password, name, firstName);
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(restAddress);
try
{
var response = await client.PostAsync(restAddress + "api/Users", newUser);
response.EnsureSuccessStatusCode();
}
catch (Exception e)
{
ExecutionConsole.WriteError(e.ToString());
}
}
}
而 Web API 中的控制器有这个功能:
// POST: api/Users
[ResponseType(typeof(User))]
public async Task<IHttpActionResult> PostUser(User user)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
db.Users.Add(user);
try
{
await db.SaveChangesAsync();
}
catch (DbUpdateException)
{
if (UserExists(user.Username))
{
return Conflict();
}
else
{
throw;
}
}
return CreatedAtRoute("DefaultApi", new { id = user.Username }, user);
}
API 返回 400(错误请求)。 Web API 目前有这样的配置:
public void Configuration(IAppBuilder appBuilder)
{
HttpConfiguration config = new HttpConfiguration();
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
appBuilder.UseWebApi(config);
}
编辑:
用户模型:
public class User
{
public User(string userName, string email, string password) : this(userName, email, password, null, null)
{
}
public User(string userName, string email, string password, string Name, string firstName)
{
this.Username = userName;
this.Email = email;
this.Password = password;
this.Name = Name;
this.firstName = firstName;
}
[Key, Required]
public string Username { get; set; }
public string Name { get; set; }
public string firstName { get; set; }
[Required]
public string Email { get; set; }
[Required]
public string Password { get; set; }
public virtual ICollection<Playlist> CreatedPlaylists { get; set; }
public virtual ICollection<Track> SavedTracks { get; set; }
}
HTTPRequest(Rest API 是我的 Web API 项目的名称):
{Method: POST, RequestUri: 'http://localhost:2468/api/Users', Version: 1.1, Content: System.Net.Http.ObjectContent`1[[RestAPI.Model.User, RestAPI, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]], Headers:
{
Content-Type: application/json; charset=utf-8
Content-Length: 143
}}
Content: {System.Net.Http.ObjectContent<RestAPI.Model.User>}
Headers: {}
Method: {POST}
Properties: Count = 0
RequestUri: {http://localhost:2468/api/Users}
Version: {1.1}
HTTP内容:
{System.Net.Http.ObjectContent<RestAPI.Model.User>}
Formatter: {System.Net.Http.Formatting.JsonMediaTypeFormatter}
Headers: {Content-Type: application/json; charset=utf-8
Content-Length: 143
}
ObjectType: {Name = "User" FullName = "RestAPI.Model.User"}
Value: {RestAPI.Model.User}
编辑#2:
响应体:
Id = 22,
Status = RanToCompletion,
Method = "{null}",
AsyncState: null
CancellationPending: false
CreationOptions: None
Exception: null
Id: 22
Result: {Message:"The request is invalid.",
ModelState:{"user.Username":["Unable to find a constructor to use for type ClAuP.RestAPI.Model.User. A class should either have a default constructor, one constructor with arguments or a constructor marked with the JsonConstructor attribute. Path 'Username', line 1, position 12."]}}"
Status: RanToCompletion
错误消息说您需要一个默认构造函数来反序列化对象。 由于您添加了自定义构造函数,这意味着除非您明确将其放在那里,否则没有空的默认构造函数。 所以你应该能够添加
public User() { }
到您的 User 类并解决该错误。
为了能够序列化和反序列化一个对象,您需要一个空的构造函数。
public class User
{
// Add this
public User()
{
}
public User(string userName, string email, string password) : this(userName, email, password, null, null)
{
}
public User(string userName, string email, string password, string Name, string firstName)
{
this.Username = userName;
this.Email = email;
this.Password = password;
this.Name = Name;
this.firstName = firstName;
}
[...]
}
创建User
类的实例后,它将通过公开给模型的公共属性填充模型。 您已经拥有公共属性,因此添加构造函数可以解决您的问题。
您必须将 [FromBody] 添加到您的方法并验证您所指的 clace 没有继承“From Body”强制您读取整个正文,如果它没有找到请求的属性,则返回 NULL [ResponseType (typeof (用户))]公共异步任务
[ResponseType (typeof (User))]
Public asynchronous task <IHttpActionResult> PostUser ([FromBody]User user)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.