gpt4 book ai didi

c# - 如何从 WebAPI Controller 操作返回不同类型的模型?

转载 作者:太空狗 更新时间:2023-10-29 22:15:30 26 4
gpt4 key购买 nike

我有一个这样的 Controller

    [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....
}
}

此处 MessageToPatientList.GetMessageToDoctorList.Get 返回不同类型的列表,比如 InboxPatientModelInboxDoctorModel

是否可以用 [ResponseType(...)] 修饰 Action ,使其可以是动态的并且可以返回不同类型的列表?

最佳答案

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

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....
}
}

关于c# - 如何从 WebAPI Controller 操作返回不同类型的模型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48206985/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com