我想使用HttpClient使用身份驗證令牌發佈到WebAPI。如何使用HttpClient發佈到WebApi?
但是我總是得到WebAPI方法的默認值,而不是我發送的實際值。
這是我的代碼:
C#控制檯應用程序:
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字符串。
當我擊中門柱方法獲得:idCommunityAmenity = 0,idHome = 0,...
感謝您的幫助。