Dotnet Custom Response Format
In this snippet, I would demonstrate about Unique Response Type Dotnet Controllers.
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc;
namespace dotnet_pokemon_review.Middleware
{
public class CustomResponseFormatAttribute : ActionFilterAttribute
{
public override void OnResultExecuting(ResultExecutingContext context)
{
if(context.Result is ObjectResult objectResult)
{
var customData = new
{
StatusCode = objectResult.StatusCode,
Data = objectResult.Value
};
context.Result = new ObjectResult(customData)
{
StatusCode = objectResult.StatusCode
};
}
base.OnResultExecuting(context);
}
}
}
// ---- In Controller
[CustomResponseFormat]
public class YourController : Controller
{
[HttpGet]
public IActionResult YourAction()
{
// Your controller action logic here
var data = new { Message = "Hello, World!" };
return Ok(data);
}
}