c# - 强类型会破坏 HTTP PUT 吗?
问题描述
我在使用 NSwag 生成的 Api C# 客户端中的更新以及如何使用 HTTP PUT 动词时遇到问题。
假设我有一个名为 customer 的 DTO
public class CustomerDTO
{
public int id { get; set; }
public string name{ get; set; }
public string email { get; set; }
}
我有一个想要修改客户电子邮件的 C# 客户端的消费者。
因此,他创建了对 CustomerPut 的调用以替换资源。
CustomerDTO customer = await CustomerGet(); // Performs a get on the entity
customer.email = "newemail@abc.com";
await CustomerPut(customer);
暂时还好。
当我决定在 CustomerViewModel 中添加一个新字段时,问题就出现了
public class CustomerDTO
{
public int id { get; set; }
public string name{ get; set; }
public string email { get; set; }
public string? likesApples {get; set;}
}
如果我这样做,我的消费者中的代码必须更新,否则他将取消设置 likesApples 属性。这意味着每次过时的客户端尝试更新某些内容时,likesApples 的值都会被删除。
是否有解决方案,这样我就不必为要添加的每个新的简单字段更新客户端代码?
解决方案
您可以编写不同的 Put API。这是一个伪代码,如果没有编译请见谅。
从 put 请求中获取 email 和 customerUpdateRequest。并使用 propertyName 和反射设置客户价值。如果您使用 EF,您可以从 DB 中选择您的客户并更改您想要的字段。
[HttpPut]
public JsonResult UpdateCustomerValues(string email, CustomerUpdateRequest request)
{
var customer = new Customer();
customer.Email=email;
PropertyInfo propertyInfo = customer.GetType().GetProperty(request.propertyName);
propertyInfo.SetValue(customer, Convert.ChangeType(request.value, propertyInfo.PropertyType), null);
}
public class CustomerUpdateRequest
{
public string propertyName{get;set;}
public string value{get;set;}
}
推荐阅读
- javascript - 在不使用循环的情况下替换内部 Javascript for 循环,而不是使用 map、filter、reduce?
- mongodb - 在 MongoDB Atlas 中使用 UI 编辑文档后,Mongoose .save() 和 .findOneAndUpdate() 出现问题
- python - TensorRT 中的converter.build() 有什么用?
- c# - 要返回的对象的一部分是在运行时子类型期间,但作为超类型从控制器返回
- c - 为什么未初始化的指针变量作为字符串会导致错误?
- python - Django - How to pull data that has been added to the SQLite database on a different branch
- r - Is there an easy way to mask passwords in RStudio using Window's internal user environment variables?
- php - Associative array to CSV where columns are dynamic
- matlab - How to find the frist occurrence of Nan value in a matlab code (m file)?
- javascript - Why is my form data not making it to the server?