WebAPI问题:用于将客户对象从客户端传递到操作

时间:2016-08-29 15:19:50

标签: c# json asp.net-web-api httpclient

我正在尝试通过web api执行crud操作。所以我将客户json从客户端传递给web api action。

这是我从客户端传递到行动的json。

{"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"}

我的网络API动作如下所示

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

这样我尝试从winform apps

中调用来自httpclient的动作
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
            }
        }

这是我从小提琴手那里做同样的错误信息。 错误消息是:

  

{&#34; Message&#34;:&#34;请求包含实体主体但没有Content-Type   头。推断的媒体类型&#39; application / octet-stream&#39;不是   支持此资源。&#34;,&#34; ExceptionMessage&#34;:&#34;没有   MediaTypeFormatter可用于读取&#39;客户&#39;   来自媒体类型的内容   &#39;应用程序/八位字节流&#39;&#34;&#34; ExceptionType&#34;:&#34; System.Net.Http.UnsupportedMediaTypeException&#34;&#34;堆栈跟踪&#34; :&#34;   在System.Net.Http.HttpContentExtensions.ReadAsAsync [T](HttpContent)   content,Type type,IEnumerable 1 formatters, IFormatterLogger formatterLogger, CancellationToken cancellationToken)\r\n at System.Net.Http.HttpContentExtensions.ReadAsAsync(HttpContent content, Type type, IEnumerable 1格式化程序,IFormatterLogger formatterLogger,   取消语音取消语句)\ r \ n at   System.Web.Http.ModelBinding.FormatterParameterBinding.ReadContentAsync(HttpRequestMessage   请求,类型类型,IEnumerable`1格式化程序,IFormatterLogger   formatterLogger,CancellationToken cancellationToken)&#34;}

现在请告诉我我的代码中出现错误的错误。

感谢

1 个答案:

答案 0 :(得分:2)

自然这个错误是因为没有将Content-Type设置为:application / json。 我已经通过这种方式实现了我的代码。

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