In this article, we will understand the implementation of IResult for custom response in minimal API[.NET6].
IResult Type:
In minimal API to return a custom response, we have to implement the 'Microsoft.AspNetCore.Http.IResult'.
class CusomtResult : IResult { public Task ExecuteAsync(HttpContext httpContext) { throw new NotImplementedException(); } }
- The 'ExecuteAsync' method gets automatically invoked, the only parameter it will have is the 'HttpContext' where we can use to append our custom response type.
Create A .NET6 Minimal API:
Let's create a .Net6 Minimal API sample project to accomplish our sample. We can use either Visual Studio 2022 or Visual Studio Code(using .NET CLI commands) to create any .NET6 application. For this demo, I'm using the 'Visual Studio Code'(using .NET CLI commands) editor.
CLI command For Minimal API Project
dotnet new webapi -minimal -o Your_Project_Name
dotnet new webapi -minimal -o Your_Project_Name
Implementing Custom Response With IResult:
Now let's implement a custom response with the help of IResult interface. For our demo let's implement a custom HTML response.
class CusomtHTMLResult : IResult { private readonly string _htmlContent; public CusomtHTMLResult(string htmlContent) { _htmlContent = htmlContent; } public async Task ExecuteAsync(HttpContext httpContext) { httpContext.Response.ContentType = MediaTypeNames.Text.Html; httpContext.Response.ContentLength = Encoding.UTF8.GetByteCount(_htmlContent); await httpContext.Response.WriteAsync(_htmlContent); } }
- (Line: 1) The 'CustomHTMLResult' implementing the 'Microsoft.AspNetCore.Http.IResult'.
- (Line: 3-7) Injecting the HTML result.
- (Line: 8) The 'ExecuteAsync' method gets automatically executed on initializing 'CustomHTMLResult' object.
- (Line: 10-12) Updating the 'HttpContext' object with our HTML response, like defining 'ContentType', 'ContentLength'.
static class CustomResultExtensions { public static IResult HtmlResponse(this IResultExtensions extensions, string html) { return new CusomtHTMLResult(html); } }
- The 'CustomResultExtions' is a static class. where we can define the extension method of our custom response.
app.MapGet("/html-custom-response", () => Results.Extensions.HtmlResponse(@" <html> <head></head> <body> <h1>Minimal API Custom HTML Response</h1> </body> </html> "));
- Here we can observe that our endpoint delegate method return type is our custom response method('HtmlResponse').
Support Me!
Buy Me A Coffee
PayPal Me
Video Session:
Wrapping Up:
Hopefully, I think this article delivered some useful information on implementing the IResult for custom response in minimal API. I love to have your feedback, suggestions, and better techniques in the comment section below.
Comments
Post a Comment