首页 > 解决方案 > 强类型会破坏 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 的值都会被删除。

是否有解决方案,这样我就不必为要添加的每个新的简单字段更新客户端代码?

标签: c#asp.net-corenswag

解决方案


您可以编写不同的 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;}

}

推荐阅读