Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/302.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# WebAPI问题:用于将客户对象从客户端传递到操作_C#_Json_Asp.net Web Api_Httpclient - Fatal编程技术网

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

C# WebAPI问题:用于将客户对象从客户端传递到操作,c#,json,asp.net-web-api,httpclient,C#,Json,Asp.net Web Api,Httpclient,我正在尝试通过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","C

我正在尝试通过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/客户”)]
公共类CustomerController:ApiController
{
[HttpPost,路线(“添加客户”)]
公共HttpResponseMessage后客户(客户)
{
customer=repository.Add(客户);
var response=Request.CreateResponse(HttpStatusCode.Created,客户);
response.ReasonPhrase=“已成功添加客户”;
字符串uri=Url.Link(“DefaultApi”,新的{customerID=customer.customerID});
response.Headers.Location=新Uri(Uri);
返回响应;
}
}
通过这种方式,我尝试从winform应用程序调用httpclient的操作
private async void btnAdd\u单击(对象发送方,事件参数e)
{
客户oCustomer=新客户
{
CustomerID=“詹姆斯”,
CompanyName=“James pvt”,
ContactName=“James”,
ContactTitle=“Sr开发者”,
地址=“盐湖”,
Region=“sect-1”,
PostalCode=“700009”,
City=“Kolinara”,
Country=“印度”,
电话=“033-8547-4789”,
传真=“033-8547-4781”
};
var fullAddress=”http://localhost:38762/api/customer/AddCustomer";
尝试
{
使用(var client=new HttpClient())
{
var serializedCustomer=JsonConvert.SerializeObject(oCustomer);
var content=new-StringContent(serializedCustomer,Encoding.UTF8,“application/json”);
使用(var response=client.PostAsync(fullAddress,content.Result)
{
if(响应。IsSuccessStatusCode)
{
var customerJsonString=await response.Content.ReadAsStringAsync();
//_Customer=JsonConvert.DeserializeObject(customerJsonString);
}
其他的
{
Console.WriteLine(“{0}({1})”,(int)response.StatusCode,response.ReasonPhrase);
var dict=JsonConvert.DeserializeObject(response.Content.ReadAsStringAsync().Result);
MessageBox.Show(dict[“Message”]);
}
}
}
}
捕获(HttpRequestException-ex)
{
//这里有什么例外吗
}
}
这是我从fiddler那里得到的错误信息。 错误消息为:

{“Message”:“请求包含一个实体体,但没有内容类型 标头。推断的媒体类型“应用程序/八位字节流”不正确 此资源支持。“,“ExceptionMessage”:“否” MediaTypeFormatter可用于读取“Customer”类型的对象 从媒体类型的内容 “应用程序/八位字节流”。“异常类型”:“System.Net.Http.UnsupportedMediaTypeException”,“StackTrace”: 在System.Net.Http.HttpContentExtensions.ReadAsAsync[T](HttpContent 内容、类型、IEnumerable
1格式化程序、IFormatterLogger
formatterLogger,CancellationToken CancellationToken)\r\n位于
System.Net.Http.HttpContentExtensions.ReadAsAsync(HttpContent内容,
类型类型,IEnumerable
1格式化程序,IFormatterLogger格式化程序记录器, CancellationToken CancellationToken)\r\n位于 System.Web.Http.ModelBinding.FormatterParameterBinding.ReadContentAsync(HttpRequestMessage 请求,类型,IEnumerable`1格式化程序,IFormatterLogger formatterLogger,CancellationToken CancellationToken)“}

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


谢谢

当然,这个错误是因为没有将内容类型设置为: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);
  });

当然,这个错误是因为没有将内容类型设置为: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);
  });

我只是在Web API项目的App_Start/WebApiConfig.cs类中添加了以下内容
config.Formatters.JsonFormatter.SupportedMediaTypes.Add(新的MediaTypeHeaderValue(“text/html”)
那么为什么我们需要再次设置application/json以使用post和客户json调用操作?config.Formatters.JsonFormatter.SupportedMediaTypes.Add(新的System.Net.Http.Headers.MediaTypeHeaderValue(“text/html”));通过设置此选项,您告诉返回json类型。您没有告诉web api您的请求类型是application/json,我设置了内容类型…请参阅我上面的代码
var content=new StringContent(serializedCustomer,Encoding.UTF8,“application/json”)
那么为什么我们需要在您的链接中再次添加相同的内容
DefaultRequestHeaders
?我只是在Web API项目的App_Start/WebApiConfig.cs类中添加了以下内容。
config.Formatters.JsonFormatter.SupportedMediaTypes.add(新的MediaTypeHeaderValue(“text/html”)
那么为什么我们需要再次设置application/json以使用post和客户json调用操作?config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new System.Net.Http.Headers.MediaTypeHeaderValue(“text/html”));通过设置此选项,您告诉返回json类型。您没有告诉web api您的请求类型是application/json,我设置了内容类型…请参阅我上面的代码
var content=new StringContent(serializedCustomer,Encoding.UTF8,“application/json”);
那么为什么我们需要在您的链接中再次添加相同的内容
DefaultRequestHeaders
?请使用“[FromBody]Customer-Customer”作为输入参数请使用“[FromBody]Customer-Customer”作为输入参数
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);
  });