Actually i solved it with a class model container which contains my model object and the additional information i need as properties (those will be automatically added to my Json):
public abstract class JsonBaseFormatter
{
public bool Success { get; set; } = true;
public int Duration { get; set; }
}
public class JsonFormatter<T> : JsonBaseFormatter
{
public T Data { get; set; }
public JsonFormatter(T data)
{
Data = data;
}
}
Then in my controller i used this class container in the HttpGet retreive method:
[HttpGet("{cd_drt_cml}")]
[ProducesResponseType(typeof(Ds_Invit_Sydrtcml), StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public ActionResult<JsonFormatter<Ds_Invit_Sydrtcml>> RetrieveOne(string cd_drt_cml)
{
var model = _ids_invit_sydrtcmlservice.RetrieveOne(cd_drt_cml);
if (model == null)
{
return NotFound();
}
var response = new JsonFormatter<Ds_Invit_Sydrtcml>(model);
return new ActionResult<JsonFormatter<Ds_Invit_Sydrtcml>>(response);
}
And then the beauty of it, I created an ActionFilter that is called automatically when http requests are sent or received by the controller:
public class ResponseTimeActionFilter : IActionFilter
{
private const string ResponseTimeKey = "ResponseTimeKey";
public void OnActionExecuting(ActionExecutingContext context)
{
// Start the timer
context.HttpContext.Items[ResponseTimeKey] = Stopwatch.StartNew();
}
public void OnActionExecuted(ActionExecutedContext context)
{
var res = context.Result as ObjectResult;
if (res != null)
{
Stopwatch stopwatch = (Stopwatch)context.HttpContext.Items[ResponseTimeKey];
// Calculate the time elapsed
var timeElapsed = stopwatch.Elapsed;
var success = context.HttpContext.Response.StatusCode == StatusCodes.Status200OK;
var json = ((ObjectResult)context.Result).Value as JsonBaseFormatter;
if (json != null)
{
json.Success = success;
json.Duration = timeElapsed.Milliseconds;
}
}
}
}
To make the filter works you have to register it in the Startup->ConfigureService method: services.AddScoped<ResponseTimeActionFilter>();
And also decorate your controller so that it automatically calls the filter at each http request operation: [ServiceFilter(typeof(ResponseTimeActionFilter))]
all infos about how filters work here https://damienbod.com/2015/09/15/asp-net-5-action-filters/
The request result can be found in attachment.