0

Let's say I have a class I would like to be returned by API:

public class MyClass
{
    ...
    public object someObject { get; set; }
    ...

    public MyClass(object someObject)
    {
        this.someObject = someObject;
    }
}

And as someObject property in this class I would like to return one or another class:

public class CustomClass1
{
    ...
}

public class CustomClass2
{
    ...
}

My API method in controller looks something like this:

[HttpGet()]
[Produces("application/json")]
[ProducesResponseType(typeof(MyClass), 200)]
public async Task<IActionResult> ApiMethod([Required] string input)
{
    if (...)
        return new OkObjectResult(new MyClass(new class CustomClass1());
    else
        return new OkObjectResult(new MyClass(new class CustomClass2());
}

But in Swagger models CustomClass1 and CustomClass2 are not specified and MyClass's property someObject is empty and looks like this: {}. Is there any way to tell OpenApi to "index" those classes as models and specify that one or another type will be returned? Possibly some alternative solution?

1 Answer 1

1

Would the below codes meet your requirement?

public class Myclass
    {
        // Contains all property of Entity1/Entity2
        public int Id { get; set; }

        public string Prop1 { get; set; }
        public string Prop2 { get; set; }
        public string Prop3 { get; set; }
        public string Prop4 { get; set; }


    }


    public class Entity1
    {
        public int Id { get; set; }

        public string Prop1 { get; set; }
        public string Prop2 { get; set; }
    }

    public class Entity2
    {
        public int Id { get; set; }

        public string Prop3 { get; set; }
        public string Prop4 { get; set; }
    }

Api:

[HttpGet]
        [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(Myclass))]
        
        public ActionResult<Myclass> GetUserEntity(int id)
        {
            object entity;
            if (somecondition)
            {
                 entity = new Entity1() { Id = 1, Prop1 = "prop1", Prop2 = "prop2" };


            }

            else
            {
                entity = new Entity2() { Id = 2, Prop3 = "prop3", Prop4 = "prop4" };
            }

            var jsonstr = System.Text.Json.JsonSerializer.Serialize(entity);

            var target = System.Text.Json.JsonSerializer.Deserialize<Myclass>(jsonstr);


            return Ok(target);
            
        }

Result:

enter image description here

Sign up to request clarification or add additional context in comments.

1 Comment

It would probably be the easiest solution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.