【发布时间】:2016-12-05 20:29:01
【问题描述】:
我正在尝试使用身份验证令牌使用 HttpClient 发布到 WebAPI。
但是,我总是在 WebAPI 方法上获得默认值,而不是我发送的实际值。
这是我的代码:
C#控制台APP:
public static async Task<string> Rent(HttpClient client, string token, int idCommunityAmenity, int idHome, DateTime startDate, DateTime endDate)
{
var request = new HttpRequestMessage(HttpMethod.Post, "http://localhost:50634/api/amenity/RentCommunityAmenity");
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
var postContent = new
{
idCommunityAmenity = idCommunityAmenity,
idHome = idHome,
startDate = startDate,
endDate = endDate
};
request.Content = new StringContent( JsonConvert.SerializeObject(postContent), Encoding.UTF8, "application/json");
var response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);
response.EnsureSuccessStatusCode();
return await response.Content.ReadAsStringAsync();
}
WebAPI
[HttpPost("RentCommunityAmenity")]
public async Task<JsonResult> Post([FromBody]int idCommunityAmenity, [FromBody]int idHome, [FromBody]DateTime startDate, [FromBody]DateTime endDate)
{
var communityAmenity = new AmenityReservation
{
IdCommunityAmenity = idCommunityAmenity,
StartDate = startDate,
EndDate = endDate,
IdHome = idHome
};
_context.AmenityReservation.Add(communityAmenity);
await _context.SaveChangesAsync();
return new JsonResult(true);
}
我的猜测是内容设置不正确,因为当我检查它时,我没有看到 json 字符串。
当我点击 post 方法时,我得到:idCommunityAmenity = 0, idHome=0,...
感谢您的帮助。
【问题讨论】:
标签: asp.net-web-api asp.net-web-api2 httpclient