如何在Restful Web API(.NET / JSON / EF6)服务器端实现部分更新(PATCH)

时间:2016-10-11 06:50:17

标签: c# json rest entity-framework-6 patch

我一直在研究一个Web API项目(Restful),其中模型(和各自的表)的大小相当大,因此绝对需要部分更新。

我已经回顾了POST对模型子节的选项,但鉴于该模型有大量字段(和自定义字段),不要认为暴露那么多URI是不可行的。

我理解使用PATCH动词,我可以允许客户端进行部分更新,但我正在努力构思我应该如何在服务器端捕获相同内容,然后找出更改的内容(将JSON发布到模型转换),以便我可以区分哪些字段被客户端显式设置为NULL(因为她想更新字段)。由于没有更新,什么是NULL。

我应该使用自定义映射器吗?或者我应该在字段级别创建通用属性并捕获状态吗?

我已经搜索过(并且仍然在做)网络和SOF.com,但是我找不到任何权威/具体的内容,所以请专业人士联系以获得反馈。

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

KevinDockx为MVC创建了处理PATCH的插件。这是nuget链接https://www.nuget.org/packages/Marvin.JsonPatch/

此插件是.NET的RFC 6902实现..

基本上当你从客户端发送json补丁时,你必须构建一系列操作

Function Overlap(RecA As Shape, RecB As Shape) As Boolean

Dim Shp1Left As Single
Dim Shp1Right As Single
Dim Shp1Top As Single
Dim Shp1Bottom As Single

Dim Shp2Left As Single
Dim Shp2Right As Single
Dim Shp2Top As Single
Dim Shp2Bottom As Single

Dim HorOverlap As Boolean
Dim VertOverlap As Boolean

Set RecA = Sheet1.Shapes("RecA")
Set RecB = Sheet1.Shapes("RecB")

With RecA
    Shp1Left = .Left
    Shp1Right = .Left + .Width
    Shp1Top = .Top
    Shp1Bottom = .Top + .Height
End With

With RecB
    Shp2Left = .Left
    Shp2Right = .Left + .Width
    Shp2Top = .Top
    Shp2Bottom = .Top + .Height
End With
''''''''''''''''''''''''''''''''''''''''''''''
' do they overlap horizontally?
If Shp1Left > Shp2Left Then
    If Shp1Left < Shp2Right Then
        HorOverlap = True
    End If
End If
If Shp1Left < Shp2Left Then
    If Shp1Right > Shp2Left Then
        HorOverlap = True
    End If
End If

' do they overlap vertically?
If Shp1Top > Shp2Top Then
    If Shp1Top < Shp2Bottom Then
        VertOverlap = True
    End If
End If
If Shp1Top < Shp2Top Then
    If Shp1Bottom > Shp2Top Then
        VertOverlap = True
    End If
End If

Overlap = HorOverlap And VertOverlap

End Function

当然,只有你想遵循规范才有意义。在其他情况下(我的意思是你自己对PATCH如何工作的理解)你必须实现自定义逻辑。

修改

我个人发现只有'替换'操作在我的用例中才有用,因为我的DTO具有扁平的性质。