【问题标题】:Controller accepting different models控制器接受不同的模型
【发布时间】:2021-10-21 21:52:16
【问题描述】:

我想根据查询参数值接受与正文不同的模型类型。

例子:

[HttpGet]
[Route("GetSystemdetails")]
public string Getdeatils([FromBody] SystemDetail sysdetails, string type)
{
    //some code here
    string details = getdetails(sysdetails); 
}

// abc model
public class abc
{
    public int UserID { get; set; }

    public string Email { get; set; }
}

//xyz model
public class xyz
{
    public int xyzid { get; set; }

    public string systemval { get; set; }

    public string snum { get; set; }
}

键入abcxyz 将拥有自己的模型。因此,基于type,我在查询参数中收到我想选择模型并继续。

示例网址:

localhost/GetSystemdetails/type=abc
localhost/GetSystemdetails/type=xyz

我想创建一个 new model SystemDetail 来保存这两个模型(xyzabc)并根据系统选择它们。

我想知道有哪些可能的方法来实现这种要求,而无需在控制器中创建多个方法(我不想更改 URL 的格式)。

【问题讨论】:

标签: c# .net asp.net-web-api microservices


【解决方案1】:

这不是开箱即用的支持。您的链接解决方案可能是您最接近的解决方案。

ASP.NET Core 在路由时不应该考虑参数的值,验证除外。

【讨论】:

    【解决方案2】:

    有几种可能的方法来做到这一点

    拥有多个模型对象

    在您提供的链接中,您可以声明多个模型对象。该网站已经给出了示例

    public class PostUserGCM
    {
        public User User { get; set; }
        public GCM GCM { get; set; }
    }
    

    但您可以使用自己的示例。

    基础模型

    您的模型可以从某些基本模型继承。如果您一次只需要一个模型并且它们有一些相似之处,那么您可以创建一个其他两个继承自的基本模型,在实现时不可知,您的用例主要在控制器内部的实例化上有所不同,而一些服务方法可以处理其他差异。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-24
      相关资源
      最近更新 更多