Sanchitos
Sanchitos

Reputation: 8591

How to Post to WebApi using HttpClient?

I am trying to post to a WebAPI using HttpClient using an authentication token.

However I am always getting default values on the WebAPI method not the actual values I am sending.

This is my code:

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);
        }

My guess is that the content is not being set up correctly, because when I inspect it I don't see the the json string.

When I hit the post method I get: idCommunityAmenity = 0, idHome=0,...

Thanks for the help.

Upvotes: 1

Views: 749

Answers (2)

Andrei Dragotoniu
Andrei Dragotoniu

Reputation: 6335

  1. create a model for the data you pass to the webapi endpoint.
  2. add all the validation to it.

something like :

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

Use whatever other validation you need on the model. DataContract and DataMember comes from System.ComponentModel.DataAnnotations which you add as a reference separately. Sometimes, depending on how your project is setup, your api will not receive data from your post because the property members don't serialize. Making sure you have those can actually help a lot.

Now in webapi you can check your model is valid like this:

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

       //your code here.
 }

Upvotes: 2

Sanchitos
Sanchitos

Reputation: 8591

This is the way I fix it.

I took the reference from this answer

Basically you have to receive an object on the WebAPI side.

Like this:

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

 }

Upvotes: 0

Related Questions