[英]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.