File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change @@ -107,9 +107,11 @@ public static IServiceCollection AddJsonApiToolkit(this IServiceCollection servi
107107 {
108108 jsonInputFormatter . SupportedMediaTypes . Add ( "application/vnd.api+json" ) ;
109109 }
110+ options . Filters . AddService < JsonApiContentTypeFilter > ( ) ;
110111 } ) ;
111112
112113 services . AddScoped < JsonApiExceptionFilter > ( ) ;
114+ services . AddScoped < JsonApiContentTypeFilter > ( ) ;
113115
114116 return services ;
115117 }
Original file line number Diff line number Diff line change 1+ using Microsoft . AspNetCore . Mvc ;
2+ using Microsoft . AspNetCore . Mvc . Filters ;
3+
4+ namespace JsonApiToolkit . Filters ;
5+
6+ /// <summary>
7+ /// A filter that sets the content type of the response to "application/vnd.api+json"
8+ /// for all JSON API responses.
9+ /// </summary>
10+ public class JsonApiContentTypeFilter : IActionFilter
11+ {
12+ private const string JsonApiMediaType = "application/vnd.api+json" ;
13+
14+ /// <summary>
15+ /// Does nothing before the action executes.
16+ /// </summary>
17+ public void OnActionExecuting ( ActionExecutingContext context )
18+ {
19+ // No action needed before executing the action
20+ }
21+
22+ /// <summary>
23+ /// Sets the content type of the response to "application/vnd.api+json"
24+ /// for all JSON API responses.
25+ /// </summary>
26+ public void OnActionExecuted ( ActionExecutedContext context )
27+ {
28+ if ( context . Result is ObjectResult objectResult )
29+ {
30+ objectResult . ContentTypes . Clear ( ) ;
31+ objectResult . ContentTypes . Add ( JsonApiMediaType ) ;
32+ }
33+ else if ( context . Result is StatusCodeResult )
34+ {
35+ context . HttpContext . Response . ContentType = JsonApiMediaType ;
36+ }
37+ }
38+ }
You can’t perform that action at this time.
0 commit comments