如何使用HttpClient发布到WebApi?

时间:2016-12-05 20:29:01

标签: asp.net-web-api asp.net-web-api2 httpclient

我正在尝试使用HttpClient使用身份验证令牌发布到WebAPI。

但是我总是在WebAPI方法上获取默认值而不是我发送的实际值。

这是我的代码:

C#Console 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,...

感谢您的帮助。

2 个答案:

答案 0 :(得分:2)

  1. 为传递给webapi端点的数据创建模型。
  2. 将所有验证添加到其中。
  3. 类似的东西:

    [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不会从您的帖子收到数据,因为酒店成员不会序列化。确保你拥有那些可以帮助很多。

    现在在webapi中,您可以检查您的模型是否有效:

    [HttpPost("RentCommunityAmenity")]
     public async Task<JsonResult> Post([FromBody] BookingModel)
     {
           if ( !ModelState.IsValid )
           {
                 return Request.CreateResponse(HttpStatusCode.BadRequest);
           }
    
           //your code here.
     }
    

答案 1 :(得分:0)

这是我修复它的方式。

我从这个toolchains

中获取了参考

基本上你必须在WebAPI端收到一个对象。

像这样:

@model YourApp.Models.ApplicationUser
<div class="page-header">
</div>
<div>
<dl class="dl-horizontal">
<dt>
@Html.DisplayNameFor(model => model.UserName)
</dt>
<dd>
@Html.DisplayFor(model => model.UserName)
</dd>
</dl>
</div>
<table class="table">
@foreach (var item in ViewBag.RoleNames)
{
    <tr>
        <td>
            @item
        </td>
    </tr>
}
</table>
相关问题