0
votes

i am trying to perform crud operation by web api. so i pass customer json from client to web api action.

this is my json which i passed from client to action.

{"CustomerID":"James","CompanyName":"jame pvt","ContactName":"James","ContactTitle":"Sr Developer","Address":"Salt lake","Region":"sect-1","PostalCode":"700009","City":"kolinara","Country":"India","Phone":"033-8547-4789","Fax":"033-8547-4781"}

my web api action looks as below

    [RoutePrefix("api/customer")]
    public class CustomerController : ApiController
    {
    [HttpPost, Route("AddCustomer")]
            public HttpResponseMessage PostCustomer(Customer customer)
            {
                customer = repository.Add(customer);
                var response = Request.CreateResponse<Customer>(HttpStatusCode.Created, customer);
                response.ReasonPhrase = "Customer successfully added";
                string uri = Url.Link("DefaultApi", new { customerID = customer.CustomerID });
                response.Headers.Location = new Uri(uri);
                return response;
            }
}

this way i try to call action from httpclient from winform apps

private async void btnAdd_Click(object sender, EventArgs e)
        {
            Customer oCustomer = new Customer
            {
                CustomerID = "James",
                CompanyName = "James pvt",
                ContactName = "James",
                ContactTitle = "Sr Developer",
                Address = "Salt lake",
                Region = "sect-1",
                PostalCode = "700009",
                City = "Kolinara",
                Country = "India",
                Phone = "033-8547-4789",
                Fax = "033-8547-4781"
            };

            var fullAddress = "http://localhost:38762/api/customer/AddCustomer";

            try
            {
                using (var client = new HttpClient())
                {
                    var serializedCustomer = JsonConvert.SerializeObject(oCustomer);
                    var content = new StringContent(serializedCustomer, Encoding.UTF8, "application/json");

                    using (var response = client.PostAsync(fullAddress, content).Result)
                    {
                        if (response.IsSuccessStatusCode)
                        {
                            var customerJsonString = await response.Content.ReadAsStringAsync();
                            //_Customer = JsonConvert.DeserializeObject<IEnumerable<Customer>>(customerJsonString);
                        }
                        else
                        {
                            Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);
                            var dict = JsonConvert.DeserializeObject<Dictionary<string, string>>(response.Content.ReadAsStringAsync().Result);
                            MessageBox.Show(dict["Message"]);
                        }
                    }
                }
            }
            catch (HttpRequestException ex)
            {
                // catch any exception here
            }
        }

this is the error message i got when i do the same from fiddler. the error msg is :

{"Message":"The request contains an entity body but no Content-Type header. The inferred media type 'application/octet-stream' is not supported for this resource.","ExceptionMessage":"No MediaTypeFormatter is available to read an object of type 'Customer' from content with media type 'application/octet-stream'.","ExceptionType":"System.Net.Http.UnsupportedMediaTypeException","StackTrace":" at System.Net.Http.HttpContentExtensions.ReadAsAsync[T](HttpContent content, Type type, IEnumerable1 formatters, IFormatterLogger formatterLogger, CancellationToken cancellationToken)\r\n at System.Net.Http.HttpContentExtensions.ReadAsAsync(HttpContent content, Type type, IEnumerable1 formatters, IFormatterLogger formatterLogger, CancellationToken cancellationToken)\r\n at System.Web.Http.ModelBinding.FormatterParameterBinding.ReadContentAsync(HttpRequestMessage request, Type type, IEnumerable`1 formatters, IFormatterLogger formatterLogger, CancellationToken cancellationToken)"}

now please tell me what is wrong in my code for which i am getting error.

thanks

1
please use "[FromBody]Customer customer" as input paramterHoutan

1 Answers

2
votes

Naturally this error beacuse of not setting Content-Type to: application/json. I have implemented my code by this way.

HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://localhost:38762/api/customer/AddCustome");
client.DefaultRequestHeaders
  .Accept
  .Add(new MediaTypeWithQualityHeaderValue("application/json"));

 HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post,"relativeAddress");
 var serializedCustomer = JsonConvert.SerializeObject(oCustomer);
                var content = new StringContent(serializedCustomer, Encoding.UTF8, "application/json");
  request.Content = content;
  client.SendAsync(request)
  .ContinueWith(responseTask =>
  {
      Console.WriteLine("Response: {0}", responseTask.Result);
  });