Skip to content

Commit ad60901

Browse files
Min API: Add IProblemDetailsService content plus app example (#35982)
* Min API: Add IProblemDetailsService content plus app sample * Re-organizing sections in minimal-apis.md * Apply suggestions from code review Added great suggestions from Mike. Co-authored-by: Mike Kistler <[email protected]> * Update aspnetcore/fundamentals/minimal-apis/10.0-samples/MinApiIproblemDetailsService/Program.cs Co-authored-by: Mike Kistler <[email protected]> * Apply suggestions from code review Added Mike's suggestion: Replace feature with name of feature. Co-authored-by: Mike Kistler <[email protected]> * Update aspnetcore/fundamentals/minimal-apis/responses.md --------- Co-authored-by: Mike Kistler <[email protected]>
1 parent d1ed37c commit ad60901

File tree

7 files changed

+149
-3
lines changed

7 files changed

+149
-3
lines changed

aspnetcore/fundamentals/minimal-apis.md

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ description: Provides an overview of minimal APIs in ASP.NET Core
55
ms.author: wpickett
66
content_well_notification: AI-contribution
77
monikerRange: '>= aspnetcore-6.0'
8-
ms.date: 05/20/2025
8+
ms.date: 08/22/2025
99
uid: fundamentals/minimal-apis
1010
ai-usage: ai-assisted
1111
---
@@ -56,7 +56,7 @@ The following sections cover request handling: routing, parameter binding, and r
5656

5757
## Routing
5858

59-
A configured `WebApplication` supports `Map{Verb}` and <xref:Microsoft.AspNetCore.Builder.EndpointRouteBuilderExtensions.MapMethods%2A> where `{Verb}` is a camel-cased HTTP method like `Get`, `Post`, `Put` or `Delete`:
59+
A configured `WebApplication` supports `Map{Verb}` and <xref:Microsoft.AspNetCore.Builder.EndpointRouteBuilderExtensions.MapMethods%2A> where `{Verb}` is a camel-cased HTTP method like `Get`, `Post`, `Put`, or `Delete`:
6060

6161
[!code-csharp[](~/fundamentals/minimal-apis/7.0-samples/WebMinAPIs/Program.cs?name=snippet_r1)]
6262

@@ -112,6 +112,17 @@ app.MapPost("/products",
112112
=> TypedResults.Ok(productId))
113113
.DisableValidation();
114114
```
115+
### Customize validation error responses using IProblemDetailsService
116+
117+
Customize error responses from minimal API validation logic with an <xref:Microsoft.AspNetCore.Http.IProblemDetailsService> implementation. Register this service in your application's service collection to enable more consistent and user-specific error responses. Support for minimal API validation was introduced in ASP.NET Core in .NET 10.
118+
119+
To implement custom validation error responses:
120+
121+
* Implement <xref:Microsoft.AspNetCore.Http.IProblemDetailsService> or use the default implementation
122+
* Register the service in the DI container
123+
* The validation system automatically uses the registered service to format validation error responses
124+
125+
For more information on customizing validation error responses with IProblemDetailsService, see <xref:fundamentals/minimal-apis/responses#customize-validation-error-responses-using-iproblemdetailsservice>.
115126

116127
## Responses
117128

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
<Project Sdk="Microsoft.NET.Sdk.Web">
2+
3+
<PropertyGroup>
4+
<TargetFramework>net10.0</TargetFramework>
5+
<Nullable>enable</Nullable>
6+
<ImplicitUsings>enable</ImplicitUsings>
7+
</PropertyGroup>
8+
9+
</Project>
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
// <snippet_register_IProblemDetailsService_implementation>
2+
using System.ComponentModel.DataAnnotations;
3+
4+
var builder = WebApplication.CreateBuilder(args);
5+
6+
builder.Services.AddProblemDetails(options =>
7+
{
8+
options.CustomizeProblemDetails = context =>
9+
{
10+
if (context.ProblemDetails.Status == 400)
11+
{
12+
context.ProblemDetails.Title = "Validation error occurred";
13+
context.ProblemDetails.Extensions["support"] = "Contact [email protected]";
14+
context.ProblemDetails.Extensions["traceId"] = Guid.NewGuid().ToString();
15+
}
16+
};
17+
});
18+
// </snippet_register_IProblemDetailsService_implementation>
19+
20+
builder.Services.AddValidation();
21+
22+
var app = builder.Build();
23+
24+
app.UseHttpsRedirection();
25+
26+
// Define endpoints
27+
app.MapGet("/", () => "Hello! Use /products endpoint to test validation with IProblemDetailsService");
28+
29+
// Products endpoint that demonstrates validation
30+
app.MapPost("/products", (Product product) =>
31+
{
32+
// If validation passes (handled automatically based on DataAnnotations)
33+
return TypedResults.Ok(product);
34+
});
35+
36+
// Explicitly trigger validation failure for testing
37+
app.MapGet("/products/test-validation-error", () =>
38+
{
39+
// Manually create an invalid product to see the validation error
40+
return TypedResults.ValidationProblem(new Dictionary<string, string[]>
41+
{
42+
{ "Name", new[] { "The Name field is required." } },
43+
{ "Price", new[] { "The field Price must be between 1 and 100." } }
44+
});
45+
});
46+
47+
app.Run();
48+
49+
// Model with validation attributes
50+
public class Product
51+
{
52+
[Required(ErrorMessage = "The Name field is required.")]
53+
public string? Name { get; set; }
54+
55+
[Range(1, 100, ErrorMessage = "The field Price must be between 1 and 100.")]
56+
public decimal Price { get; set; }
57+
}
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
@HostAddress = https://localhost:7134
2+
3+
### Test the home endpoint
4+
GET {{HostAddress}}
5+
6+
### Test products endpoint with valid data
7+
POST {{HostAddress}}/products
8+
Content-Type: application/json
9+
10+
{
11+
"name": "Test Product",
12+
"price": 50
13+
}
14+
15+
### Test products endpoint with invalid data (missing name)
16+
POST {{HostAddress}}/products
17+
Content-Type: application/json
18+
19+
{
20+
"price": 50
21+
}
22+
23+
### Test products endpoint with invalid data (price out of range)
24+
POST {{HostAddress}}/products
25+
Content-Type: application/json
26+
27+
{
28+
"name": "Test Product",
29+
"price": 200
30+
}
31+
32+
### Test explicit validation error endpoint
33+
GET {{HostAddress}}/products/test-validation-error
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
{
2+
"Logging": {
3+
"LogLevel": {
4+
"Default": "Information",
5+
"Microsoft.AspNetCore": "Warning"
6+
}
7+
}
8+
}
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
{
2+
"Logging": {
3+
"LogLevel": {
4+
"Default": "Information",
5+
"Microsoft.AspNetCore": "Warning"
6+
}
7+
},
8+
"AllowedHosts": "*"
9+
}

aspnetcore/fundamentals/minimal-apis/responses.md

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,9 @@ author: brunolins16
44
description: Learn how to create responses for minimal APIs in ASP.NET Core.
55
ms.author: brolivei
66
monikerRange: '>= aspnetcore-7.0'
7-
ms.date: 05/09/2025
7+
ms.date: 08/22/2025
88
uid: fundamentals/minimal-apis/responses
9+
ai-usage: ai-assisted
910
---
1011

1112
# How to create responses in Minimal API apps
@@ -154,6 +155,24 @@ The preceding example returns a 500 status code.
154155

155156
:::code language="csharp" source="~/fundamentals/minimal-apis/9.0-samples/Snippets/Program.cs" id="snippet_12":::
156157

158+
#### Customize validation error responses using IProblemDetailsService
159+
160+
Customize error responses from minimal API validation logic with an <xref:Microsoft.AspNetCore.Http.IProblemDetailsService> implementation. Register this service in your application's service collection to enable more consistent and user-specific error responses. Support for minimal API validation was introduced in ASP.NET Core in .NET 10.
161+
162+
To implement custom validation error responses:
163+
164+
* Implement <xref:Microsoft.AspNetCore.Http.IProblemDetailsService> or use the default implementation
165+
* Register the service in the DI container
166+
* The validation system automatically uses the registered service to format validation error responses
167+
168+
The following example shows how to register and configure the <xref:Microsoft.AspNetCore.Http.IProblemDetailsService> to customize validation error responses:
169+
170+
:::code language="csharp" source="~/fundamentals/minimal-apis/10.0-samples/MinApiIproblemDetailsService/Program.cs" id="snippet_register_IProblemDetailsService_implementation" :::
171+
172+
When a validation error occurs, the <xref:Microsoft.AspNetCore.Http.IProblemDetailsService> will be used to generate the error response, including any customizations added in the `CustomizeProblemDetails` callback.
173+
174+
For a complete app example, see the [Minimal API sample app](https://github.com/dotnet/AspNetCore.Docs/blob/main/aspnetcore/fundamentals/minimal-apis/10.0-samples/MinApiIproblemDetailsService/Program.cs) demonstrating how to customize validation error responses using the <xref:Microsoft.AspNetCore.Http.IProblemDetailsService> in ASP.NET Core Minimal APIs.
175+
157176
#### Text
158177

159178
:::code language="csharp" source="~/fundamentals/minimal-apis/9.0-samples/Snippets/Program.cs" id="snippet_08":::

0 commit comments

Comments
 (0)