I have a simple .net core app that emits an API output.
My Configure
method is pretty simple :
public void Configure(IApplicationBuilder app, IWebHostEnvironment env )
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints => { endpoints.MapControllers(); });
}
This is the current output from the API :
Just for testing purpose, I want to add HTML tag before and after the response :
Something like ( edited manually in DOM ) :
So I've added this :
public void Configure(IApplicationBuilder app, IWebHostEnvironment env )
{
app.Use(async (context, next) =>
{
await context.Response.WriteAsync("<b> Hi</b>");
await next ();
await context.Response.WriteAsync("<b> Bye </b>");
});
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints => { endpoints.MapControllers(); });
}
But when I run it , I get :
fail: Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware1 An unhandled exception has occurred while executing the request. System.InvalidOperationException: Headers are read-only, response has already started. With this HTML :
I've been searching for a solution in SO but didn't find, how to do it.
Question:
Why is it happening? I thought I can control the pipeline and do whatever I want it via calling next()
on the pipeline.
How can I add my custom HTML tags before and after?
Edit:
If I move the code to the end of the Configure
method, I see the regular output , without getting the exception, but without the HTML tags.
Edit #2 :
I've also tried with OnStarting
event , but still , no success (I get an empty page):
app.Use(async (context, next) =>
{
context.Response.OnStarting(async state =>
{
if (state is HttpContext httpContext)
{
var request = httpContext.Request;
var response = httpContext.Response;
await response .WriteAsync("<b> Bye </b>"); // <----
}
}, context);
await next();
});