Dotnet Custom Response Format

January 14, 2024

C# & .NET

Dotnet Custom Response Format

Thuta Sann

Thuta Sann

Unique Response Type Dotnet Controllers


Share This Snippet To :

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); } }

Cookie

I baked some cookies that you have to accept, if you want to enjoy my portfolio.
In order to gather information and make improvements, I should use some third-party cookies too, Can I?