Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions JsonApiToolkit/Extensions/ServiceCollectionExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -107,9 +107,11 @@ public static IServiceCollection AddJsonApiToolkit(this IServiceCollection servi
{
jsonInputFormatter.SupportedMediaTypes.Add("application/vnd.api+json");
}
options.Filters.AddService<JsonApiContentTypeFilter>();
});

services.AddScoped<JsonApiExceptionFilter>();
services.AddScoped<JsonApiContentTypeFilter>();

return services;
}
Expand Down
38 changes: 38 additions & 0 deletions JsonApiToolkit/Filters/JsonApiContentTypeFilter.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;

namespace JsonApiToolkit.Filters;

/// <summary>
/// A filter that sets the content type of the response to "application/vnd.api+json"
/// for all JSON API responses.
/// </summary>
public class JsonApiContentTypeFilter : IActionFilter
{
private const string JsonApiMediaType = "application/vnd.api+json";

/// <summary>
/// Does nothing before the action executes.
/// </summary>
public void OnActionExecuting(ActionExecutingContext context)
{
// No action needed before executing the action
}

/// <summary>
/// Sets the content type of the response to "application/vnd.api+json"
/// for all JSON API responses.
/// </summary>
public void OnActionExecuted(ActionExecutedContext context)
{
if (context.Result is ObjectResult objectResult)
{
objectResult.ContentTypes.Clear();
objectResult.ContentTypes.Add(JsonApiMediaType);
}
else if (context.Result is StatusCodeResult)
{
context.HttpContext.Response.ContentType = JsonApiMediaType;
}
}
}