Tôi đang cố gắng để có được phản ứng JSON này với một tiêu đề Ihttpstatus có mã 201 và giữ IHttpActionResult làm kiểu trả về phương thức của tôi.Làm thế nào để trở về từ một phương pháp IHttpActionResult một biến tùy chỉnh?
JSON Tôi muốn quay trở lại:
{ "CustomerID": 324}
phương pháp của tôi:
[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 trả về:
"ID" : 324, "Ngày": "201 4-06-18T17: 35: 07.8095813-07: 00 ",
Dưới đây là một số lợi nhuận mà tôi đã thử hoặc đã cho tôi lỗi vô giá trị hoặc đã cho tôi phản hồi tương tự như ví dụ ở trên .
return Created<Customer>(Request.RequestUri + NewCustomer.ID.ToString(), NewCustomer.ID.ToString());
return CreatedAtRoute<Customer>("DefaultApi", new { CustomerID = NewCustomer.ID }, NewCustomer);
Với phương thức loại giải thích, phương pháp này có thể được giải quyết như bên dưới. Tuy nhiên tôi muốn sử dụng một IHttpActionResult:
public HttpResponseMessage CreateCustomer()
{
Customer NewCustomer = CustomerRepository.Add();
return Request.CreateResponse(HttpStatusCode.Created, new { CustomerID = NewCustomer.ID });
}
Cảm ơn bạn. Đó là một câu trả lời thực sự tốt. Nhưng tôi không hiểu tại sao "Tạo()" yêu cầu vị trí và nó là gì. – user3754602
Nó thêm tiêu đề 'Vị trí' vào phản hồi chứa URL vào thực thể mới được tạo. – Jasen