我试图用Ihttpstatus标头获取此
JSON响应,该标头声明代码201并保持IHttpActionResult作为我的方法返回类型.
我想要的JSON返回:
{“CustomerID”: 324}
我的方法:
[Route("api/createcustomer")] [HttpPost] [ResponseType(typeof(Customer))] public IHttpActionResult CreateCustomer() { Customer NewCustomer = CustomerRepository.Add(); return CreatedAtRoute<Customer>("DefaultApi",new controller="customercontroller",CustomerID = NewCustomer.ID },NewCustomer); }
JSON返回:
“ID”: 324,
“Date”: “2014-06-18T17:35:07.8095813-07:00”,
以下是我尝试过的一些回报,或者给了我uri null错误,或者给了我类似于上面例子的回复.
return Created<Customer>(Request.RequestUri + NewCustomer.ID.ToString(),NewCustomer.ID.ToString()); return CreatedAtRoute<Customer>("DefaultApi",new { CustomerID = NewCustomer.ID },NewCustomer);
使用httpresponsemessage类型方法,可以解决此问题,如下所示.但是我想使用IHttpActionResult:
public HttpResponseMessage CreateCustomer() { Customer NewCustomer = CustomerRepository.Add(); return Request.CreateResponse(HttpStatusCode.Created,new { CustomerID = NewCustomer.ID }); }
解决方法
这会得到你的结果:
[Route("api/createcustomer")] [HttpPost] //[ResponseType(typeof(Customer))] public IHttpActionResult CreateCustomer() { ... string location = Request.RequestUri + "/" + NewCustomer.ID.ToString(); return Created(location,new { CustomerId = NewCustomer.ID }); }
现在ResponseType不匹配.如果需要此属性,则需要创建新的返回类型,而不是使用匿名类型.
public class CreatedCustomerResponse { public int CustomerId { get; set; } } [Route("api/createcustomer")] [HttpPost] [ResponseType(typeof(CreatedCustomerResponse))] public IHttpActionResult CreateCustomer() { ... string location = Request.RequestUri + "/" + NewCustomer.ID.ToString(); return Created(location,new CreatedCustomerResponse { CustomerId = NewCustomer.ID }); }
另一种方法是使用Customer类上的DataContractAttribute来控制序列化.
[DataContract(Name="Customer")] public class Customer { [DataMember(Name="CustomerId")] public int ID { get; set; } // DataMember omitted public DateTime? Date { get; set; } }
然后只返回创建的模型
return Created(location,NewCustomer); // or return CreatedAtRoute<Customer>("DefaultApi",NewCustomer);
原文地址:https://www.jb51.cc/csharp/92117.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。