1

I need to make an HTTP endpoint with different return types based on query params. There are several options to do that:

Return an object with one property set and the rest equal to null:

public class ResponseModel
{
    Type1 Property1 { set; get; }
    Type2 Property2 { set; get; }
    Type3 Property3 { set; get; }
}

...

return new ResponseModel { Field2 = responseObj };

Return an object with enum or string indicating the return type and a string with jsonified object:

public enum ReturnType
{
    Type1, Type2, Type3
}

public class ResponseModel
{
    ReturnType Type { set; get; }
    string Payload { set; get; }
}

...

return new ResponseModel { Type = ReturnType.Type2, Payload = responseObj.Jsonify() };

I might be able to come up with other solutions, however, I would like to know if there are any general recommendations and/or best practices when implementing such an endpoint. Thanks in advance.

  • c# forces you to have a single type on whatever service method you are exposing, so why are you exposing three methods behind a single endpoint? – Ewan Apr 2 '18 at 10:28
  • If all the responses are essentialy the same thing (is-a) you could use inheritance instead of composition. Maybe I'm biased by the so many REST API I do in my job, but my recommendation would be don't go that way. Keep the things as simple as possible, even if that means to duplicate some lines of code. – Laiv Apr 2 '18 at 10:54
  • If the responses really are the same thing, but you want to return it in a different format, then content negotiation might be what you are looking for. – pinki Apr 5 '18 at 11:44
  • This might be more at home on stack overflow – richzilla Apr 6 '18 at 12:36
  • Presumably, youre attempting to serialise an object hierarchy into a single JSON model? – richzilla Apr 6 '18 at 12:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.