42 lines
1.4 KiB
C#
42 lines
1.4 KiB
C#
using Microsoft.AspNetCore.Mvc.Infrastructure;
|
|
using Microsoft.AspNetCore.Mvc;
|
|
using System.Text.Json;
|
|
using System.Text.Json.Serialization;
|
|
using System.Text;
|
|
|
|
public class CustomJsonResultExecutor : IActionResultExecutor<JsonResult>
|
|
{
|
|
private readonly IHttpContextAccessor _httpContextAccessor;
|
|
private readonly ILogger<CustomJsonResultExecutor> _logger;
|
|
|
|
public CustomJsonResultExecutor(IHttpContextAccessor httpContextAccessor, ILogger<CustomJsonResultExecutor> logger)
|
|
{
|
|
_httpContextAccessor = httpContextAccessor;
|
|
_logger = logger;
|
|
}
|
|
|
|
public async Task ExecuteAsync(ActionContext context, JsonResult result)
|
|
{
|
|
var response = context.HttpContext.Response;
|
|
response.ContentType = "application/json; charset=utf-8";
|
|
|
|
var requestPath = context.HttpContext.Request.Path;
|
|
|
|
var options = new JsonSerializerOptions
|
|
{
|
|
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
|
|
WriteIndented = false
|
|
};
|
|
|
|
if (requestPath.HasValue && requestPath.StartsWithSegments("/api", StringComparison.OrdinalIgnoreCase))
|
|
{
|
|
// API → enum به صورت string
|
|
options.Converters.Add(new JsonStringEnumConverter());
|
|
}
|
|
// Else: Razor → enum بدون converter (یعنی عدد)
|
|
|
|
var json = JsonSerializer.Serialize(result.Value, options);
|
|
|
|
await response.WriteAsync(json, Encoding.UTF8);
|
|
}
|
|
} |