-
Notifications
You must be signed in to change notification settings - Fork 25.2k
JsonPatch System.Text.Json - based .NET 10 Preview 4 update #35571
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
20 commits
Select commit
Hold shift + click to select a range
7463a15
JsonPatch System.Text.Json Update .NET 10 Preview 4
wadepickett fffc025
Fixed link, updated doc meta data
wadepickett 45f0a2f
Fix link
wadepickett 3ac8957
Added Mitigating security risks section to version 9 of article
wadepickett 2637fb4
Added mitigating security section to all previous versions of article
wadepickett 4a9dc04
Removed bold on test behavior
wadepickett 175a38d
Moved Action Method code section back in
wadepickett 9d7a34f
Corrected NuGet link, and mentioned the package link again at top
wadepickett c0ea3dd
Small edits
wadepickett 47eab6a
Added xref links for all API mention.
wadepickett f331b66
Per review: For v9 moved up moniker to avoid repeate of security section
wadepickett 7fae625
Per Review: Removed JsonPatch Operations section
wadepickett 6f9b1fa
Fixed dupe mitigate security section
wadepickett 766520f
Apply suggestions from code review
wadepickett 57d4db4
Applied changes per tdystra recommendations
wadepickett edd8b74
Removed real app warning
wadepickett 5a9b06e
Added Mike's sample and updated action method section
wadepickett 4a6deac
Moved app sample to JsonPatchSample folder
wadepickett 6604d2c
Update aspnetcore/web-api/jsonpatch.md
wadepickett 511a0b6
Updated JsonPatch. to JsonPatch.SystemTextJson. throughout jsonpatch.md
wadepickett File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Large diffs are not rendered by default.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
57 changes: 57 additions & 0 deletions
57
aspnetcore/web-api/jsonpatch/samples/10.x/JsonPatchSample/Controllers/CustomerController.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,57 @@ | ||
using Microsoft.AspNetCore.Mvc; | ||
using Microsoft.AspNetCore.JsonPatch.SystemTextJson; | ||
|
||
using App.Data; | ||
using App.Models; | ||
|
||
namespace App.Controllers; | ||
|
||
[ApiController] | ||
[Route("/api/customers")] | ||
public class CustomerController : ControllerBase | ||
{ | ||
[HttpGet("{id}", Name = "GetCustomer")] | ||
public Customer Get(AppDb db, string id) | ||
{ | ||
// Retrieve the customer by ID | ||
var customer = db.Customers.FirstOrDefault(c => c.Id == id); | ||
|
||
// Return 404 Not Found if customer doesn't exist | ||
if (customer == null) | ||
{ | ||
Response.StatusCode = 404; | ||
return null; | ||
} | ||
|
||
return customer; | ||
} | ||
|
||
// <snippet_PatchAction> | ||
[HttpPatch("{id}", Name = "UpdateCustomer")] | ||
public IActionResult Update(AppDb db, string id, [FromBody] JsonPatchDocument<Customer> patchDoc) | ||
{ | ||
// Retrieve the customer by ID | ||
var customer = db.Customers.FirstOrDefault(c => c.Id == id); | ||
|
||
// Return 404 Not Found if customer doesn't exist | ||
if (customer == null) | ||
{ | ||
return NotFound(); | ||
} | ||
|
||
patchDoc.ApplyTo(customer, jsonPatchError => | ||
{ | ||
var key = jsonPatchError.AffectedObject.GetType().Name; | ||
ModelState.AddModelError(key, jsonPatchError.ErrorMessage); | ||
} | ||
); | ||
|
||
if (!ModelState.IsValid) | ||
{ | ||
return BadRequest(ModelState); | ||
} | ||
|
||
return new ObjectResult(customer); | ||
} | ||
// </snippet_PatchAction> | ||
} |
52 changes: 52 additions & 0 deletions
52
aspnetcore/web-api/jsonpatch/samples/10.x/JsonPatchSample/CustomerApi.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,52 @@ | ||
using Microsoft.AspNetCore.Http.HttpResults; | ||
using Microsoft.AspNetCore.JsonPatch.SystemTextJson; | ||
using Microsoft.EntityFrameworkCore; | ||
|
||
using App.Data; | ||
using App.Models; | ||
|
||
internal static class CustomerApi { | ||
public static void MapCustomerApi(this IEndpointRouteBuilder routes) | ||
{ | ||
var group = routes.MapGroup("/customers").WithTags("Customers"); | ||
|
||
group.MapGet("/{id}", async Task<Results<Ok<Customer>, NotFound>> (AppDb db, string id) => | ||
{ | ||
return await db.Customers.Include(c => c.Orders).FirstOrDefaultAsync(c => c.Id == id) is Customer customer | ||
? TypedResults.Ok(customer) | ||
: TypedResults.NotFound(); | ||
}); | ||
|
||
group.MapPatch("/{id}", async Task<Results<Ok<Customer>,NotFound,BadRequest, ValidationProblem>> (AppDb db, string id, | ||
JsonPatchDocument<Customer> patchDoc) => | ||
{ | ||
var customer = await db.Customers.Include(c => c.Orders).FirstOrDefaultAsync(c => c.Id == id); | ||
if (customer is null) | ||
{ | ||
return TypedResults.NotFound(); | ||
} | ||
if (patchDoc != null) | ||
{ | ||
Dictionary<string, string[]>? errors = null; | ||
patchDoc.ApplyTo(customer, jsonPatchError => | ||
{ | ||
errors ??= new (); | ||
var key = jsonPatchError.AffectedObject.GetType().Name; | ||
if (!errors.ContainsKey(key)) | ||
{ | ||
errors.Add(key, new string[] { }); | ||
} | ||
errors[key] = errors[key].Append(jsonPatchError.ErrorMessage).ToArray(); | ||
}); | ||
if (errors != null) | ||
{ | ||
return TypedResults.ValidationProblem(errors); | ||
} | ||
await db.SaveChangesAsync(); | ||
} | ||
|
||
return TypedResults.Ok(customer); | ||
}) | ||
.Accepts<JsonPatchDocument<Customer>>("application/json-patch+json"); | ||
} | ||
} |
22 changes: 22 additions & 0 deletions
22
aspnetcore/web-api/jsonpatch/samples/10.x/JsonPatchSample/Data/AppDb.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,22 @@ | ||
using Microsoft.EntityFrameworkCore; | ||
using App.Models; | ||
|
||
namespace App.Data; | ||
|
||
public class AppDb : DbContext | ||
{ | ||
public required DbSet<Customer> Customers { get; set; } | ||
|
||
public AppDb(DbContextOptions<AppDb> options) : base(options) | ||
{ | ||
} | ||
|
||
protected override void OnModelCreating(ModelBuilder modelBuilder) | ||
{ | ||
base.OnModelCreating(modelBuilder); | ||
|
||
// Configure entity relationships here if needed | ||
modelBuilder.Entity<Customer>() | ||
.HasKey(c => c.Id); | ||
} | ||
} |
53 changes: 53 additions & 0 deletions
53
aspnetcore/web-api/jsonpatch/samples/10.x/JsonPatchSample/Data/AppDbSeeder.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,53 @@ | ||
using App.Models; | ||
using Microsoft.EntityFrameworkCore; | ||
|
||
namespace App.Data; | ||
|
||
public static class AppDbSeeder | ||
{ | ||
public static async Task Seed(WebApplication app) | ||
{ | ||
// Create and seed the database | ||
using (var scope = app.Services.CreateScope()) | ||
{ | ||
var services = scope.ServiceProvider; | ||
var context = services.GetRequiredService<AppDb>(); | ||
context.Database.EnsureCreated(); | ||
|
||
if (context.Customers.Any()) | ||
{ | ||
return; | ||
} | ||
|
||
Customer[] customers = { | ||
new Customer | ||
{ | ||
Id = "1", | ||
Name = "John Doe", | ||
Email = "john.doe@example.com", | ||
PhoneNumber = "555-123-4567", | ||
Address = "123 Main St, Anytown, USA" | ||
}, | ||
new Customer | ||
{ | ||
Id = "2", | ||
Name = "Jane Smith", | ||
Email = "jane.smith@example.com", | ||
PhoneNumber = "555-987-6543", | ||
Address = "456 Oak Ave, Somewhere, USA" | ||
}, | ||
new Customer | ||
{ | ||
Id = "3", | ||
Name = "Bob Johnson", | ||
Email = "bob.johnson@example.com", | ||
PhoneNumber = "555-555-5555", | ||
Address = "789 Pine Rd, Elsewhere, USA" | ||
} | ||
}; | ||
|
||
await context.Customers.AddRangeAsync(customers); | ||
await context.SaveChangesAsync(); | ||
} | ||
} | ||
} |
16 changes: 16 additions & 0 deletions
16
aspnetcore/web-api/jsonpatch/samples/10.x/JsonPatchSample/JsonPatchSample.csproj
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,16 @@ | ||
<Project Sdk="Microsoft.NET.Sdk.Web"> | ||
|
||
<PropertyGroup> | ||
<TargetFramework>net10.0</TargetFramework> | ||
<Nullable>enable</Nullable> | ||
<ImplicitUsings>enable</ImplicitUsings> | ||
</PropertyGroup> | ||
|
||
<ItemGroup> | ||
<PackageReference Include="Microsoft.AspNetCore.JsonPatch.SystemTextJson" Version="10.0.0-preview.5.25277.114" /> | ||
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="10.0.0-preview.5.25277.114" /> | ||
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="10.0.0-preview.5.25277.114" /> | ||
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="10.0.0-preview.5.25277.114" /> | ||
</ItemGroup> | ||
|
||
</Project> |
76 changes: 76 additions & 0 deletions
76
aspnetcore/web-api/jsonpatch/samples/10.x/JsonPatchSample/JsonPatchSample.http
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,76 @@ | ||
@HostAddress = http://localhost:5221 | ||
|
||
GET {{HostAddress}}/openapi/v1.json | ||
Accept: application/json | ||
|
||
### | ||
|
||
GET {{HostAddress}}/api/customers/1 | ||
Accept: application/json | ||
|
||
### | ||
|
||
PATCH {{HostAddress}}/api/customers/1 | ||
Content-Type: application/json-patch+json | ||
Accept: application/json | ||
|
||
[ | ||
{ | ||
"op": "replace", | ||
"path": "/email", | ||
"value": "foo@bar.baz" | ||
} | ||
] | ||
|
||
### | ||
|
||
# Error response | ||
|
||
PATCH {{HostAddress}}/api/customers/1 | ||
Content-Type: application/json-patch+json | ||
Accept: application/json | ||
|
||
[ | ||
{ | ||
"op": "add", | ||
"path": "/foobar", | ||
"value": 42 | ||
} | ||
] | ||
|
||
### | ||
### Minimal API requests | ||
### | ||
|
||
GET {{HostAddress}}/customers/1 | ||
Accept: application/json | ||
|
||
### | ||
|
||
PATCH {{HostAddress}}/customers/1 | ||
Content-Type: application/json-patch+json | ||
Accept: application/json | ||
|
||
[ | ||
{ | ||
"op": "replace", | ||
"path": "/email", | ||
"value": "foo@bar.baz" | ||
} | ||
] | ||
|
||
### | ||
|
||
# Error response | ||
|
||
PATCH {{HostAddress}}/customers/1 | ||
Content-Type: application/json-patch+json | ||
Accept: application/json | ||
|
||
[ | ||
{ | ||
"op": "add", | ||
"path": "/foobar", | ||
"value": 42 | ||
} | ||
] |
16 changes: 16 additions & 0 deletions
16
aspnetcore/web-api/jsonpatch/samples/10.x/JsonPatchSample/Models/Customer.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,16 @@ | ||
namespace App.Models; | ||
|
||
public class Customer | ||
{ | ||
public string Id { get; set; } | ||
public string? Name { get; set; } | ||
public string? Email { get; set; } | ||
public string? PhoneNumber { get; set; } | ||
public string? Address { get; set; } | ||
public List<Order>? Orders { get; set; } | ||
|
||
public Customer() | ||
{ | ||
Id = Guid.NewGuid().ToString(); | ||
} | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.