Skip to content

Commit 4cc978e

Browse files
Add JsonApiContentTypeFilter to set response content type
1 parent a8af9dd commit 4cc978e

2 files changed

Lines changed: 40 additions & 0 deletions

File tree

JsonApiToolkit/Extensions/ServiceCollectionExtensions.cs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff 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
}
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
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+
}

0 commit comments

Comments
 (0)