在ASP.NET Core 3.1的Web API中,处理多种类型的JSON对象的方法如下:
public abstract class BaseRequestModel { public int Id { get; set; } public string Name { get; set; } }
public class EmployeeCreateRequestModel : BaseRequestModel { public string Department { get; set; } public int Salary { get; set; } }
public class CustomerRequestModel : BaseRequestModel { public string Email { get; set; } public string Phone { get; set; } }
[HttpPost] public IActionResult Create([JsonConverter(typeof(JsonInheritanceConverter), "type")] BaseRequestModel requestModel) { // Code to create Employee or Customer depending on 'type' property in request return Ok(); }
{ "id": 123, "type": "EmployeeCreateRequestModel", "name": "John Doe", "department": "IT", "salary": 50000 }
或
{ "id": 456, "type": "CustomerRequestModel", "name": "Jane Doe", "email": "jane.doe@example.com", "phone": "1234567890" }
通过这种方式,我们可以处理多种类型的JSON对象。我们应该在创建请求模型时使用必要的属性和方法来保持代码的清晰度和维护性。