简体   繁体   English

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

[英]How to return different types of model from a WebAPI controller action?

I have a controller like this 我有这样的控制器

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

Here MessageToPatientList.Get and MessageToDoctorList.Get return list of different types say InboxPatientModel and InboxDoctorModel . 这里MessageToPatientList.GetMessageToDoctorList.Get返回不同类型的列表,说InboxPatientModelInboxDoctorModel

Is it possible to decorate the action with [ResponseType(...)] so that it can be dynamic and different types of list can be returned? 是否可以使用[ResponseType(...)]修饰操作,以便它可以是动态的,并且可以返回不同类型的列表?

You could merge the different types of lists; 您可以合并不同类型的列表;

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

The URL is already different when searching for doctors and patients, so there is no benefit in having a single action. 在搜索医生和患者时,URL已经不同,因此单一操作没有任何好处。

Just write two Actions "GetDoctors" and "GetPatients" which return the types you want. 只需编写两个动作“GetDoctors”和“GetPatients”,它们返回您想要的类型。

[ResponseType(typeof(List<InboxPatientModel>))]
[Route("~/api/Messages/searchpatients")]
public IHttpActionResult GetPatients(string searchTerm = "")
{
}

[ResponseType(typeof(List<InboxDoctorModel>))]
[Route("~/api/Messages/searchdoctors")]
public IHttpActionResult GetDoctors(string searchTerm = "")
{
}

Your code will run just fine. 你的代码运行得很好。 The [ResponseType] attribute is only used to give hints for the Web API documentation page and tools like Swagger. [ResponseType]属性仅用于为Web API文档页面和Swagger等工具提供提示。

While the attribute has AllowMultiple=true in its AttributeUsage attribute, I don't think those documentation tools support this. 虽然该属性在其AttributeUsage属性中具有AllowMultiple=true ,但我认为这些文档工具不支持此功能。

And they shouldn't. 他们不应该。 Returning different types from an API depending on the size of the moon, the day of the week or the value of some parameters is a hell to implement, a hell to document and a hell to consume. 从API中返回不同的类型,取决于月亮的大小,星期几或某些参数的值是一个地狱实现,一个地狱文件和一个地狱消费。

Instead consider reviewing the design. 而是考虑审查设计。 Why should the actual type of a message change depending on who is the recipient? 为什么邮件的实际类型会根据谁是收件人而改变? What is different between the two types of messages? 什么两种类型的消息之间有什么不同?

On the contrary, find properties they share . 相反,找到他们共享的属性。 Then extract a base class, say, Message , and decorate the method with an attribute [ResponseType(typeof(Message))] . 然后提取一个基类,比如Message ,并用属性[ResponseType(typeof(Message))]装饰该方法。

Each resource (patient and doctor) should have its own controller action. 每个资源(患者和医生)都应该有自己的控制器动作。 I would do this: 我会这样做:

1) Create two different controller actions: one for InboxPatientModel and another one for InboxDoctorModel. 1)创建两个不同的控制器动作:一个用于InboxPatientModel,另一个用于InboxDoctorModel。

2) At the client-side you determine, based on "messageFor", which controller action you need to call. 2)在客户端,您可以根据“messageFor”确定需要调用哪个控制器操作。

3) Eeach controller action would have a different ResponseType. 3)Eeach控制器动作将具有不同的ResponseType。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何从WebApi动作返回html页面? - How to return html page from WebApi action? ASP.NET从视图返回不同的枚举类型到同一控制器操作 - ASP.NET return different enum types from the view to the same controller action 如何访问从另一个控制器动作中的一个控制器动作检索的模型 - How to access a model retrieved from one controller action in a different controller action 如何通过使用CORS的WebAPI控制器将来自其他域的值放入模型中? - How do I put a value from a different domain in my Model through a WebAPI Controller using CORS? .NET MVC4-在同一API控制器操作中从模型返回不同的字段子集 - .NET MVC4 - Return different subset of fields from Model in the same API controller action WebAPI控制器相同的动作不同的参数 - WebAPI controller same action different parameters .net如何从MVC Controller调用webapi操作 - .net How to Call a webapi action from MVC Controller 如何将模型传递给WebApi控制器? - How to pass model to WebApi controller? 如何使用IHttpActionResult接口从WebApi 2操作返回html文档? - How to return an html document from WebApi 2 action using IHttpActionResult interface? 如何从Webapi httppost控制器方法返回对象 - How to return an object from a webapi httppost controller moethod
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM