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

本文关键字:客户端 操作 对象 问题 客户 WebAPI | 更新日期: 2023-09-27 18:04:37

我试图通过web api执行crud操作。因此,我将客户端json传递给web API操作。

这是我的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"}

我的web 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应用程序的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
            }
        }

这是我从fiddler中执行相同操作时得到的错误消息。错误信息是:

{"Message":"请求包含实体主体,但没有Content-Type。头。推断的媒体类型'application/octet-stream'不是,"ExceptionMessage":"否MediaTypeFormatter可用于读取"Customer"类型的对象。从具有媒体类型的内容应用程序/八进制。"、"ExceptionType":"System.Net.Http.UnsupportedMediaTypeException"、"加":"在System.Net.Http.HttpContentExtensions.ReadAsAsync [T] (HttpContentIEnumerable 1 formatters, IFormatterLogger formatterLogger, CancellationToken cancellationToken)'r'n at System.Net.Http.HttpContentExtensions.ReadAsAsync(HttpContent content, Type type, IEnumerable 1 formatters, IFormatterLogger formatterLogger,CancellationToken CancellationToken)'r'n atSystem.Web.Http.ModelBinding.FormatterParameterBinding.ReadContentAsync (HttpRequestMessageIEnumerable ' 1 formatters, IFormatterLoggerformatterLogger, CancellationToken"}

现在请告诉我在我的代码是什么错了,我得到错误。

谢谢

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

这个错误自然是因为没有将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);
  });