强类型会破坏HTTP PUT吗?

时间:2019-03-01 18:36:03

标签: c# asp.net-core nswag

我在用NSwag生成的Api C#客户端中进行更新以及如何使用HTTP PUT动词时遇到了麻烦。

假设我有一个称为客户的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的值都会被删除。

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

2 个答案:

答案 0 :(得分:1)

  

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

您的API版本。通过使用PUT,您可以将给定资源分配给给定标识符,从而覆盖该资源的先前版本。

向资源中添加新字段需要新的合同,因此需要新的API版本。

如果您要继续添加新字段并允许部分更新,请查看PATCH。

答案 1 :(得分:1)

您可以编写其他Put API。这是一个伪代码,如果不能编译,请原谅我。

从放置请求中接收电子邮件和customerUpdateRequest。 并使用propertyName和Reflection设置客户价值。 如果使用EF,则可以从数据库中选择客户,然后更改所需的字段。

[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;}

}