I am trying to get this JSON response with an Ihttpstatus header that states code 201 and keep IHttpActionResult as my method return type.
JSON I want returned:
{"CustomerID": 324}
My method:
[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 returned:
"ID": 324, "Date": "2014-06-18T17:35:07.8095813-07:00",
Here are some of the returns I've tried that either gave me uri null error or have given me a response similar to the example one above.
return Created<Customer>(Request.RequestUri + NewCustomer.ID.ToString(), NewCustomer.ID.ToString());
return CreatedAtRoute<Customer>("DefaultApi", new { CustomerID = NewCustomer.ID }, NewCustomer);
With an httpresponsemessage type method this can be solved as shown below. However I want to use an IHttpActionResult:
public HttpResponseMessage CreateCustomer()
{
Customer NewCustomer = CustomerRepository.Add();
return Request.CreateResponse(HttpStatusCode.Created, new { CustomerID = NewCustomer.ID });
}
Best How To :
This will get you your result:
[Route("api/createcustomer")]
[HttpPost]
//[ResponseType(typeof(Customer))]
public IHttpActionResult CreateCustomer()
{
...
string location = Request.RequestUri + "/" + NewCustomer.ID.ToString();
return Created(location, new { CustomerId = NewCustomer.ID });
}
Now the ResponseType
does not match. If you need this attribute you'll need to create a new return type instead of using an anonymous type.
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 });
}
Another way to do this is to use the DataContractAttribute
on your Customer class to control the serialization.
[DataContract(Name="Customer")]
public class Customer
{
[DataMember(Name="CustomerId")]
public int ID { get; set; }
// DataMember omitted
public DateTime? Date { get; set; }
}
Then just return the created model
return Created(location, NewCustomer);
// or
return CreatedAtRoute<Customer>("DefaultApi", new controller="customercontroller", CustomerID = NewCustomer.ID }, NewCustomer);