Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/273.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# Net核心控制器方法的动态参数_C#_Api_Asp.net Core - Fatal编程技术网

C# Net核心控制器方法的动态参数

C# Net核心控制器方法的动态参数,c#,api,asp.net-core,C#,Api,Asp.net Core,我有一个具有特定属性的类对象调用CustomerBase.cs。它充当其他两个类的基类:Customer.cs和Vendor.cs。i、 e public class Customer: CustomerBase public class Vendor: CustomerBase 我有一个控制器方法如下: [HttpPost("CustomerData")] public async Task<CustomerBase> CustomerDataAsync(

我有一个具有特定属性的类对象调用CustomerBase.cs。它充当其他两个类的基类:Customer.cs和Vendor.cs。i、 e

public class Customer: CustomerBase
public class Vendor: CustomerBase
我有一个控制器方法如下:

 [HttpPost("CustomerData")]
 public async Task<CustomerBase> CustomerDataAsync(CustomerBase customerBaseParam)
 { }
[HttpPost(“客户数据”)]
公共异步任务CustomerDataAsync(CustomerBase CustomerBase Separam)
{ }
当另一个web用户调用此api控制器时,Json body参数将包含rootobject的$Type。它可以包含供应商或客户,也可以仅包含CustomerBase。现在,即使我将Vendor对象作为参数传递,它也只保留customerbasegram的customerBase属性。与作为参数发送的客户对象相同。如何根据即将引入的Json body参数更改customerBaseParam的类型


我正在使用Newtonsoft。

而不是让MVC为您解析JSON结果,而是接收一个
JObject
并找到标识您正在处理的JSON对象类型的字段。这将让您决定将其解析为什么类型

注意:您可以将其设计为MVC中间件的一部分,以便将其抽象化

[HttpPost("CustomerData")]
public async Task<CustomerBase> CustomerDataAsync(JObject customerBaseJson)
{
    var customerBaseIdentifier = customerBaseJson["fieldNameWithinTheJsonPayload"];

    //This should really be a strategy pattern to adhere to the SOLID open close principle.
    switch(customerBaseIdentifier) {
        case "type 1":
            var type1Object = JsonConvert.Deserialize<Type1>(customerBaseJson);
            break;
        case ...
    }
}


[HttpPost(“客户数据”)]
公共异步任务CustomerDataAsync(JObject customerBaseJson)
{
var customerBaseIdentifier=customerBaseJson[“fieldNameWithinTheJsonPayload”];
//这应该是一种真正坚持稳健开合原则的战略模式。
开关(客户识别器){
案例“第1类”:
var type1Object=JsonConvert.Deserialize(customerBaseJson);
打破
案例
}
}

如果您使用的是Newtonsoft.Json或System.Text.Json,答案会有所不同。您需要指定我正在使用Newtonsoft.Json