如何从WebAPI控制器操作返回不同类型的模型?

Nit*_*esh 6 c# asp.net-mvc asp.net-web-api

我有这样的控制器

    [ResponseType(typeof(List<InboxPatientModel>))]
    [Route("~/api/Messages/search")]
    public IHttpActionResult GetSearch(string serchTerm = "", string messageFor = "p")
    {
        try
        {
            if(messageFor == "p")
            {
                var inboxMessages = MessageToPatientList.Get(serchTerm);
                return Ok(inboxMessages);
            }
            else
            {
                var outboxMessages = MessageToDoctorList.Get(serchTerm);
                return Ok(outboxMessages);
            }
        }
        catch (Exception ex)
        {
             //some code for exception handling....
        }
    }
Run Code Online (Sandbox Code Playgroud)

这里MessageToPatientList.GetMessageToDoctorList.Get不同类型的返回列表说InboxPatientModelInboxDoctorModel.

是否可以装饰动​​作,[ResponseType(...)]以便它可以是动态的,并且可以返回不同类型的列表?

luc*_*cky 6

您可以合并不同类型的列表;

public class PatientModel
{
    public List<InboxPatientModel> Patients { get; set; }

    public List<InboxDoctorModel> Doctors { get; set; }
}

[ResponseType(typeof(PatientModel))]
[Route("~/api/Messages/search")]
public IHttpActionResult GetSearch(string serchTerm = "", string messageFor = "p")
{
    try
    {
        var patientModel = new PatientModel();
        if (messageFor == "p")
        {
            var inboxMessages = MessageToPatientList.Get(serchTerm);
            patientModel.Patients = inboxMessages;
        }
        else
        {
            var outboxMessages = MessageToDoctorList.Get(serchTerm);
            patientModel.Doctors = inboxMessages;
        }
        return Ok(patientModel);
    }
    catch (Exception ex)
    {
        //some code for exception handling....
    }
}
Run Code Online (Sandbox Code Playgroud)