What is the correct way to pass an object to WebApi RC controller

Posted by Diver Dan on Stack Overflow See other posts from Stack Overflow or by Diver Dan
Published on 2012-06-06T00:53:19Z Indexed on 2012/06/06 4:40 UTC
Read the original article Hit count: 454

I have a webapi project running rc

I have a very basic controlller like

 [System.Web.Http.HttpPost]
    public void Update(Business business)
    {
        //if (business.Id == Guid.Empty)
        //{
        //    throw new HttpResponseException("Business ID not provided", HttpStatusCode.BadRequest);
        //}

         _repository.Update(business);
        //if (!isUpdated)
        //{
        //    throw new HttpResponseException("Business not found", HttpStatusCode.NotFound);
        //}
    }

I found an example using HttpClient however it doesnt work with rc

    using (var client = new HttpClient())
        {
            try
            {
               string url = string.Format("{0}{1}", ConfigurationManager.AppSettings["ApiBaseUrl"].ToString(),apiMethod);

                HttpRequestMessage request = new HttpRequestMessage();
                MediaTypeFormatter[] formatter = new MediaTypeFormatter[] { new JsonMediaTypeFormatter() };

                var content = request.CreateContent<Business>(
                    business, 
                    MediaTypeHeaderValue.Parse("application/json"),
                    formatter, new FormatterSelector());
                HttpResponseMessage response = client.PostAsync(url, content).Result;
                return response.Content.ToString();
            }
            catch (Exception ex)
            {
                return null;
            }

        }

I get an error

Method not found: 'Void System.Net.Http.Headers.HttpHeaders.AddWithoutValidation(System.String, System.String)'.

Passing the data from jquery is a piece of cake however I need call the api from code behind vs client side.

Can someone point me in the right direction for calling the webapi?

Thank you

© Stack Overflow or respective owner

Related posts about c#

Related posts about c#-4.0