Return a complex object in a call to the REST API

I have a POST Web API method that excludes a custom complex MyObjectRequest object as a parameter and returns a custom complex MyObjectResponse object. The MyObjectResponse object has a custom complex Token object as a property.

 public class MyObjectRequest { public string AppName { get; set; } public string Username { get; set; } public string Password { get; set; } public string AppIdentifier { get; set; } } public class MyObjectResponse { public bool Authenticated { get; set; } public Token AccessToken { get; set; } } public class Token { public string Id { get; set; } public string ExpirationDate { get; set; } } 

I have an API API where, when a user makes an HTTP POST request, I want to return MyObjectResponse .

 public class MyCustomController : Controller { public MyObjectResponse Post([FromBody] MyObjectRequest request) { //do my work here } } 

Is this the right way to create my signature MyCustomController API?

+7
rest asp.net-mvc asp.net-web-api
source share
2 answers

That you can certainly work. I tend to wrap these objects in an HttpResponseMessage , as shown below:

  [HttpPost] public HttpResponseMessage Post([FromBody] MyObjectRequest request) { if (ModelState.IsValid) // and if you have any other checks { var myObjectResponse = new MyObjectResponse(); // in your case this will be result of some service method and then return Request.CreateResponse(HttpStatusCode.Created, myObjectResponse); } return Request.CreateResponse(HttpStatusCode.BadRequest); } [HttpPut] public HttpResponseMessage Update([FromBody] UserModel userModel) { if (ModelState.IsValid) { var myObjectResponse = new MyObjectResponse(); // in your case this will be result of some service method and then return Request.CreateResponse(HttpStatusCode.Accepted); } return Request.CreateResponse(HttpStatusCode.BadRequest); } [HttpGet] public HttpResponseMessage Get(int id) { var myObjectResponse = GetObjectFromDb(id); // in your case this will be result of some service method and then if(myObjectResponse == null) return Request.CreateResponse(HttpStatusCode.NotFound); return Request.CreateResponse(HttpStatusCode.OK, myObjectResponse); } 

Thus, the client can simply look at the status code and decide what to do with the response without trying to deserialize it. You can get more information about HttpStatusCodes in this MSDN article .

They added more methods like ApiController.Ok to WebApi2. For more information, you can take a look at this ASP.NET WEB API page.

+9
source share

Yes, that’s fine, since the signature is api

+1
source share

All Articles