I have a Web API POST method that excepts a custom complex object MyObjectRequest
as a parameter and returns a custom complex object MyObjectResponse
. The MyObjectResponse
object has custom complex object Token
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 Web API controller where when the user makes a HTTP POST call, I want to return the MyObjectResponse
.
public class MyCustomController : Controller
{
public MyObjectResponse Post([FromBody] MyObjectRequest request)
{
//do my work here
}
}
Is this the correct way of making my MyCustomController
API signature?
What you have certainly can work. I tend to wrap those objects in the HttpResponseMessage
like 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. 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. 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. Then...
if(myObjectResponse == null)
return Request.CreateResponse(HttpStatusCode.NotFound);
return Request.CreateResponse(HttpStatusCode.OK, myObjectResponse);
}
This way the client can just look at the status code and decide what to do with the response without actually trying to deserialize it. You can get more info on HttpStatusCodes at this MSDN article.
They have added more methods such as ApiController.Ok
in WebApi2. For more information, you can take a look at this ASP.NET WEB API overview page.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With