如何使用 HttpClient Post 到 Web Api?
How to Post to WebApi using HttpClient?
我正在尝试 post 使用身份验证令牌使用 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 字符串。
当我点击 post 方法时,我得到:idCommunityAmenity = 0, idHome=0,...
感谢您的帮助。
我就是这样解决的。
我参考了这个 answer
基本上你必须在 WebAPI 端接收一个对象。
像这样:
[HttpPost("RentCommunityAmenity")]
public JsonResult Post([FromBody]MyModel value)
{
}
public class MyModel
{
public int idCommunityAmenity { get; set; }
public int idHome { get; set; }
public DateTime startDate { get; set; }
public DateTime endDate { get; set; }
}
- 为您传递到 Webapi 端点的数据创建一个模型。
- 为其添加所有验证。
类似于:
[DataContract]
public sealed Class BookingModel
{
[Required]
[DataMember]
public int IdCommunityAmenity { get; set; }
[DataMember]
public DateTime StartDate { get;set;}
[DataMember]
public DateTime EndDate { get; set; }
[Required]
[DataMember]
public int IdHome { get; set;}
}
在模型上使用您需要的任何其他验证。 DataContract 和 DataMember 来自 System.ComponentModel.DataAnnotations,您将其单独添加为参考。有时,根据您的项目设置方式,您的 api 不会从您的 post 接收数据,因为 属性 成员不序列化。确保你拥有这些实际上会有很大帮助。
现在在网络中api您可以像这样检查您的模型是否有效:
[HttpPost("RentCommunityAmenity")]
public async Task<JsonResult> Post([FromBody] BookingModel)
{
if ( !ModelState.IsValid )
{
return Request.CreateResponse(HttpStatusCode.BadRequest);
}
//your code here.
}
我正在尝试 post 使用身份验证令牌使用 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 字符串。
当我点击 post 方法时,我得到:idCommunityAmenity = 0, idHome=0,...
感谢您的帮助。
我就是这样解决的。
我参考了这个 answer
基本上你必须在 WebAPI 端接收一个对象。
像这样:
[HttpPost("RentCommunityAmenity")]
public JsonResult Post([FromBody]MyModel value)
{
}
public class MyModel
{
public int idCommunityAmenity { get; set; }
public int idHome { get; set; }
public DateTime startDate { get; set; }
public DateTime endDate { get; set; }
}
- 为您传递到 Webapi 端点的数据创建一个模型。
- 为其添加所有验证。
类似于:
[DataContract]
public sealed Class BookingModel
{
[Required]
[DataMember]
public int IdCommunityAmenity { get; set; }
[DataMember]
public DateTime StartDate { get;set;}
[DataMember]
public DateTime EndDate { get; set; }
[Required]
[DataMember]
public int IdHome { get; set;}
}
在模型上使用您需要的任何其他验证。 DataContract 和 DataMember 来自 System.ComponentModel.DataAnnotations,您将其单独添加为参考。有时,根据您的项目设置方式,您的 api 不会从您的 post 接收数据,因为 属性 成员不序列化。确保你拥有这些实际上会有很大帮助。
现在在网络中api您可以像这样检查您的模型是否有效:
[HttpPost("RentCommunityAmenity")]
public async Task<JsonResult> Post([FromBody] BookingModel)
{
if ( !ModelState.IsValid )
{
return Request.CreateResponse(HttpStatusCode.BadRequest);
}
//your code here.
}