• Stars
    star
    173
  • Rank 220,124 (Top 5 %)
  • Language
    C#
  • License
    MIT License
  • Created about 10 years ago
  • Updated over 2 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

JSON Patch (JsonPatchDocument) RFC 6902 implementation for .NET

JSON Patch for .NET (Web API / clients)

JSON Patch (JsonPatchDocument) RFC 6902 implementation for .NET to easily allow & apply partial REST-ful service (through Web API) updates from any client (portable class library).

NuGet package: https://www.nuget.org/packages/Marvin.JsonPatch

This component supports staticly typed objects. Dynamically typed objects are supported as well: have a look at Marvin.JsonPatch.Dynamic (https://github.com/KevinDockx/JsonPatch.Dynamic).

Important: if you're using ASP.NET Core, you don't need this component - I've been working with Microsoft on integrating this into ASP.NET Core. Have a look at http://blog.kevindockx.com/post/Partial-Updates-for-Your-RESTful-API-with-JsonPatch-in-the-new-ASP-NET-5.aspx for more information, or have a look at http://benfoster.io/blog/aspnet-core-json-patch-partial-api-updates for a more recent post on this.

JSON Patch (https://tools.ietf.org/html/rfc6902) defines a JSON document structure for expressing a sequence of operations to apply to a JavaScript Object Notation (JSON) document; it is suitable for use with the HTTP PATCH method. The "application/json-patch+json" media type is used to identify such patch documents.

One of the things this can be used for is partial updates for REST-ful API's, or, to quote the IETF: "This format is also potentially useful in other cases in which it is necessary to make partial updates to a JSON document or to a data structure that has similar constraints (i.e., they can be serialized as an object or an array using the JSON grammar)."

That's what this package is all about. Web API supports the HttpPatch method, but there's currently no implementation of the JsonPatchDocument in .NET, making it hard to pass in a set of changes that have to be applied - especially if you're working cross-platform and standardization of your API is essential.

It consists of two parts:

  • on the client (consumer of the API): the JsonPatchDocument / JsonPatchDocument class to build what's essentially a change set to be applied to your object on your API side.
  • at (Web) API level: an ApplyTo method to apply those changes to your objects.

This combination should make partial update support for your RESTful API a breeze.

Here's how to use it:

  • Build a patch document on the client. You can use the operations as described in the IETF document: Add, Remove, Replace, Copy, Move. Test support is planned.
JsonPatchDocument<DTO.Expense> patchDoc = new JsonPatchDocument<DTO.Expense>();
patchDoc.Replace(e => e.Description, expense.Description);

// serialize
var serializedItemToUpdate = JsonConvert.SerializeObject(patchDoc);

// create the patch request
var method = new HttpMethod("PATCH");
var request = new HttpRequestMessage(method, "api/expenses/" + id)
{
    Content = new StringContent(serializedItemToUpdate,
    System.Text.Encoding.Unicode, "application/json")
};

// send it, using an HttpClient instance
client.SendAsync(request);
  • On your API, in the patch method (accept document as parameter & use ApplyTo method)
[Route("api/expenses/{id}")]
[HttpPatch]
public IHttpActionResult Patch(int id, [FromBody]JsonPatchDocument<DTO.Expense> expensePatchDocument)
{
      // get the expense from the repository
      var expense = _repository.GetExpense(id);

      // apply the patch document 
      expensePatchDocument.ApplyTo(expense);

      // changes have been applied.  Submit to backend, ... 
}

If you want to provide your own adapter (responsible for applying the operations to your objects), create a new class that implements the IObjectAdapter interface, and pass in an instance of that class in the ApplyTo method.

A few more examples of how you can create a JsonPatchDocument:

JsonPatchDocument<SimpleDTO> patchDoc = new JsonPatchDocument<SimpleDTO>();

// add "4" to a list of integers at position 0
patchDoc.Add<int>(o => o.IntegerList, 4, 0);

// add "5" to the end of that list
patchDoc.Add<int>(o => o.IntegerList, 5);

// remove the current value of StringProperty
patchDoc.Remove<string>(o => o.StringProperty);

// remove the value at position two from a list of integers
patchDoc.Remove<int>(o => o.IntegerList, 2);

// replace StringProperty with value "B"
patchDoc.Replace<string>(o => o.StringProperty, "B");

// replace value at position 4 in a list of integers with value 5
patchDoc.Replace<int>(o => o.IntegerList, 5, 4);

//copy value IntegerValue to position 0 in a list of integers
patchDoc.Copy<int>(o => o.IntegerValue, o => o.IntegerList, 0);

// move the integers at position 0 in a list of integers to position 1 in that same list
patchDoc.Move<int>(o => o.IntegerList, 0, o => o.IntegerList, 1);

To create a JsonPatchDocument directly in JSON:

[
    { "op": "add", "path": "/foo", "value": "bar"},
    { "op": "replace", "path": "/baz", "value": "boo" }
]

As the package is distributed as a Portable Class library, you can use it from (ASP) .NET (4+), Windows Phone (8.1), Windows Store apps (8+), Xamarin, ...

Any and all comments, issues, ... are welcome. :-)

More Repositories

1

HttpCacheHeaders

ASP.NET Core middleware that adds HttpCache headers to responses (Cache-Control, Expires, ETag, Last-Modified), and implements cache expiration & validation models
C#
266
star
2

AspNetCore6WebAPIFundamentals

Fully functioning sample code for my ASP.NET Core 6 Web API Fundamentals course
C#
259
star
3

BuildingRESTfulAPIAspNetCore3

Fully functioning sample application accompanying my Building a RESTful API with ASP.NET Core 3 course
C#
224
star
4

CSharp10DesignPatterns

Fully functioning sample code for my C#10 Design Patterns course
C#
153
star
5

SecuringAspNetCore3WithOAuth2AndOIDC

Fully functioning finished sample code for my Securing ASP.NET Core 3 with OAuth2 and OpenID Connect course
C#
122
star
6

ImplementingAdvancedRESTfulConcernsAspNetCore3

Fully functioning sample application accompanying my Implementing Advanced RESTful Concerns with ASP.NET Core 3 course
C#
115
star
7

SecuringAspNetCore6WithOAuth2AndOIDC

Fully functioning finished sample code for my Securing ASP.NET Core 6 with OAuth2 and OpenID Connect course
C#
94
star
8

RESTfulAPIAspNetCore_Course

Building a RESTful API with ASP.NET Core starter files
C#
93
star
9

SecuringAspNetCore2WithOAuth2AndOIDC

Fully functioning finished sample code for my Securing ASP.NET Core 2 with OAuth2 and OpenID Connect course
C#
71
star
10

OpenIDConnectInDepth

OpenID Connect code sample (Angular 5, ASP.NET Core 3.0, IdentityServer4) containing SSOn/Out, reference tokens, custom grants and multi-tenancy.
C#
65
star
11

StreamExtensions

A set of helper extension methods (on Stream) for working with streams. Particularly useful for interaction with an API through HttpClient.
C#
60
star
12

AngularASPNetCoreBusinessApplications

Fully functioning finished sample code for my Building Business Applications with Angular and ASP.NET Core course
C#
56
star
13

BuildingAsyncAPIAspNetCore

Fully functioning finished sample code for my Building an Async API with ASP.NET Core course
C#
54
star
14

DocumentingAspNetCoreApisWithOpenAPI

Fully functioning finished sample code for my Documenting an ASP.NET Core API with OpenAPI / Swagger course
C#
53
star
15

AspNetCore6WebAPIDeepDive

Fully functioning sample and starter files for my ASP.NET Core 6 Web API Deep Dive course
C#
47
star
16

AspNetCoreWebApiFundamentals

Fully functioning sample code for my ASP.NET Core Web API Fundamentals course, currently targeting .NET 8.
C#
46
star
17

AspNetCoreAsyncBestPracticesJetBrainsWebinar

Demo code for my webinar at Jetbrains on async best practices in ASP.NET Core
C#
45
star
18

UnitTestingAspNetCore6WebAPI

Fully functioning sample code for my Unit Testing an ASP.NET Core 6 Web API course
C#
44
star
19

HttpClientInNetCore

Fully functioning finished sample code for my Using HttpClient to Consume APIs in .NET Core course
C#
42
star
20

AspNetCoreAsyncBestPractices

Demo code for my "Best Practices for Building Async APIs with ASP.NET Core" session
C#
39
star
21

APIAspNetCore_Course

Starter files and fully functioning finished sample for my Building Your First API with ASP.NET Core course
C#
39
star
22

DealingWithCredentialsWhenSecuringAspNetCore3

Starter files and fully finished sample code for my Dealing with Credentials when Securing an ASP.NET Core 3 Application course at Pluralsight.
C#
32
star
23

BlazorAuthenticationAndAuthorization

Fully functioning finished sample code for my Authentication and Authorization in Blazor Applications course
C#
31
star
24

SecuringMicroservicesAspNetCore

Fully functioning starter & finished sample code for my "Securing Microservices in ASP.NET Core 3" course
C#
30
star
25

CSharpDesignPatterns

Fully functioning sample code for my C# Design Patterns course, currently targeting .NET 8.
C#
29
star
26

UsingHttpClientInDotNet

Fully functioning finished sample code for my Using HttpClient to Consume APIs in .NET course
C#
28
star
27

AspNetCoreAsyncAPI

Fully async version of the CityInfo demo project from my Building Your First API with ASP.NET Core course at Pluralsight. Many thanks to @petersantiago for this!
C#
27
star
28

SecuringBlazorClientSideApplications

Fully functioning sample application accompanying my Securing Blazor Client-side Applications course.
C#
26
star
29

ApiSecurityInDepth

Sample implementing reference token support, token exchange, impersonation and delegation and enhanced client authentication with private key JWTs
C#
26
star
30

HttpCache

Marvin.HttpCache is a complete implementation of the RFC2616 Http Caching standard for use with HttpClient, for all .NET Framework platforms (Windows Store, Windows Phone, WPF, WinForms, Console apps). Have a look around for the current status and to know what's yet to be implemented.
C#
26
star
31

BuildingAnODataAPIAspNetCore

Building an OData API in ASP.NET Core (.NET 5 and .NET Core 3.1)
C#
25
star
32

SecuringBlazorServerSideApplications

Fully functioning sample application accompanying my Securing Blazor Server-side Applications course.
C#
24
star
33

BlazorWASMSecurityBestPractices

Sample showing a best practice security approach for Blazor WASM apps via the BFF pattern
C#
23
star
34

DocumentingAspNetCore6API

Starter files & fully functioning finished sample code for my Documenting an ASP.NET Core 6 Web API using Swagger course.
C#
23
star
35

TestingWithEFCore

Fully functioning finished sample code for my Testing With EF Core course
C#
22
star
36

UnitTestingAspNetCoreWebApi

Fully functioning sample code for my Unit Testing an ASP.NET Core Web API course, over at Pluralsight, currently targeting .NET 8.
C#
22
star
37

DevelopingAsyncWebAPIAspNetCore6

Starter and fully finished sample solution for my Developing an Asynchronous Web API with ASP.NET Core 6 course, over at Pluralsight.
C#
21
star
38

BuildingAspNetCore7MinimalAPIs

Fully functioning sample code for my "Building ASP.NET Core 7 Minimal APIs" course
C#
19
star
39

CleanCodeResultFilterSample

Sample of using ResultFilter and ValueTuple when building an API with ASP.NET Core
C#
18
star
40

SecuringAspNetCoreWithOAuth2andOIDC

Starter files & fully functioning finished sample code for my Securing ASP.NET Core with OAuth2 and OpenID Connect course, currently targeting .NET 8.
C#
18
star
41

AspNetCoreWebAPIDeepDive

Fully functioning sample and starter files for my ASP.NET Core Web API Deep Dive course, currently targeting .NET 8.
C#
16
star
42

ReflectionInCSharp

Fully functioning sample for my "Using Reflection in a C# Application: Best Practices" course at Pluralsight
C#
15
star
43

GeneratingCodeAndTestingAspNetCoreApis

Fully functioning finished sample code for my Using Swagger / OpenAPI for Generating Client Side Code and API Tests in ASP.NET Core course
C#
15
star
44

AccessingAPIsWithHttpClientDotNet6

Fully functioning sample and starter files for my Accessing APIs with HttpClient in .NET 6 course
C#
14
star
45

XamarinFormsOIDCSample

Xamarin Forms OAuth 2.0 / OpenID Connect Sample with IdentityServer3
C#
14
star
46

UnitTestingAspNetCoreMVC

Fully functioning sample code for my Unit Testing an ASP.NET Core MVC Web Application course, over at Pluralsight, currently targeting .NET 8.
C#
10
star
47

UnitTestingAspNetCore6MVC

Fully functioning sample code for my Unit Testing an ASP.NET Core 6 MVC Web Application course
C#
10
star
48

ConsumingAnODataAPI

Fully functioning starter and finished sample solution for my Consuming an OData v4 API course
C#
10
star
49

BuildingAspNetCoreMinimalApis

Starter files & fully functioning finished sample code for my Building ASP.NET Core Minimal APIs course, currently targeting .NET 8.
C#
10
star
50

CSharp10Reflection

Finished sample code for my C# 10 Reflection course
C#
9
star
51

HttpClientInDepth

Code for my "An in-depth look at HttpClient" session at Techorama 2019
C#
9
star
52

Sprotify_Demo

Demo project for the ASP.NET Core DevStories sessions (building an API, web app & securing it).
CSS
9
star
53

ODataV4_Course

Building a Consistent RESTful API with OData V4 in ASP.NET starter files
C#
9
star
54

JsonPatch.Dynamic

Support for dynamically typed objects for Marvin.JsonPatch (Json Patch Document RFC 6902 implementation for .NET)
C#
8
star
55

SecurityPatternsForMicroservices

Code samples: various security patterns for microservices, with Ocelot as API Gateway and Duende.IdentityServer as IDP.
C#
8
star
56

AccessingApisWithHttpClient

Fully functioning finished sample and starter files for my Accessing APIs with HttpClient in .NET course, currently targeting .NET 8.
C#
8
star
57

AuthNZinBlazor

Starter files & fully functioning finished sample code for my Authentication and Authorization in ASP.NET Core Blazor course, currently targeting .NET 8.
HTML
6
star
58

ExtendingOAuthAndOpenIdConnect

Code for my session on extending OAuth & OpenId Connect. Contains samples for private key JWT, token encryption, proof of possession access tokens, singed authorization requests and more.
C#
6
star
59

JsonPatchInAspNet5

Example of how to use JsonPatch in ASP .NET 5 (with ASP .NET 5 Web API, ASP .NET MVC 5 and 6 clients)
PowerShell
6
star
60

OAuth2OIDCAngularASPNET_Course

These are the starter files for my "OAuth2 and OpenID Connect Strategies for Angular and ASP.NET" course at Pluralsight.
C#
6
star
61

DevelopingAsynchronousAspNetCoreWebApi

Fully functioning sample code for my Developing an Asynchronous ASP.NET Core Web API, over at Pluralsight, currently targeting .NET 8.
C#
6
star
62

Marvin.Polly.Cache.HttpCache

Cache provider for Polly supporting the Http Cache standard
C#
5
star
63

DocumentingAspNetCoreWebApiUsingSwagger

Starter files & fully functioning finished sample code for my Documenting an ASP.NET Core Web API using Swagger course, currently targeting .NET 8.
C#
5
star
64

SecuringAspNetCoreWithOAuth2andOIDC_Course

Starter demo files for my Securing ASP.NET Core with OAuth2 and OpenID Connect course
C#
5
star
65

AngularOIDC_Techorama2016

Demo code for my Techorama 2016 session: "Angular, OAuth2 and OpenID Connect, Heaven or Hell?"
JavaScript
5
star
66

TwoStepsAuthenticator.NETStandard

Port of https://github.com/glacasa/TwoStepsAuthenticator by https://github.com/glacasa to .NET Standard 1.6.
C#
4
star
67

Techorama_2017

Demo code for my "REST - Just the Hard Parts" session at Techorama 2017
C#
2
star
68

CSharpReflection

Fully functioning sample application accompanying my C# Reflection course, over at Pluralsight, currently targeting .NET 8.
C#
2
star
69

SigningAndEncryption

Samples for signing and encrypting tokens, generating a jwkset, ... in ASP.NET Core
C#
1
star