My code returns an object:
public async Task<IHttpActionResult> GetAnswers(int userTestQuestionId)
{
return Ok(new AnswerToClientDTO
{
AnswerGridCorrect = answerGridCorrect,
Result = result,
UpdateRowCount = updateRowCount
});
Here is the code for the AnswerToClientDTO which is only used in the one place in my application:
public class AnswerToClientDTO
{
public string AnswerGridCorrect { get; set; }
public int UpdateRowCount { get; set; }
public string Result { get; set; }
}
Is it possible for me to return an anonymous object where I do not have to declare a class from an ASP.NET WEb API method?
In WebAPI you can pass any object to Ok()
, which can be formatted by a configured formatter, so this should be valid:
public IHttpActionResult GetStuff()
{
return Ok( new {
AnswerGridCorrect = answerGridCorrect,
Result = result,
UpdateRowCount = updateRowCount
} );
}
Technically, yes you can provided you use object
or dynamic
. That being said it is not a good idea. Also, if you are using this for a WebAPI like you mentioned (such as a REST or SOAP service via WCF) this would be a bad idea since the serialization from the HTTP call / to response won't know the proper formatting to use to send data back as JSON or XML.
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