How to return a user variable from the IHttpActionResult method?

I am trying to get this JSON response with an Ihttpstatus header that contains 201 code and saves IHttpActionResult as the return type of the method.

JSON I want to return:

{"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 my results that either gave me a uri null error or gave me an answer similar to the above example.

 return Created<Customer>(Request.RequestUri + NewCustomer.ID.ToString(), NewCustomer.ID.ToString()); return CreatedAtRoute<Customer>("DefaultApi", new { CustomerID = NewCustomer.ID }, NewCustomer); 

Using a method like httpresponsemessage can solve this, as shown below. However, I want to use IHttpActionResult:

 public HttpResponseMessage CreateCustomer() { Customer NewCustomer = CustomerRepository.Add(); return Request.CreateResponse(HttpStatusCode.Created, new { CustomerID = NewCustomer.ID }); } 
+6
source share
1 answer

This will give 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 ResponseType does not match. If you need this attribute, you will 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 in your Customer class to control 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); 
+9
source

Source: https://habr.com/ru/post/971027/


All Articles