【问题标题】:How to Post to WebApi using HttpClient?如何使用 HttpClient 发布到 Web Api?
【发布时间】: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


    【解决方案1】:
    1. 为您传递给 webapi 端点的数据创建一个模型。
    2. 向其中添加所有验证。

    类似:

    [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.
     }
    

    【讨论】:

      【解决方案2】:

      这就是我修复它的方式。

      我从这个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; }
      
       }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-08-10
        • 2019-05-10
        • 2011-09-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多