gpt4 book ai didi

c# - 在asp.net核心响应之前和之后附加自定义HTML输出?

转载 作者:行者123 更新时间:2023-12-04 01:03:01 25 4
gpt4 key购买 nike

我有一个简单的 .net 核心应用程序,它发出一个 API 输出。
我的 Configure方法很简单:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env  )
{

if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints => { endpoints.MapControllers(); });
}
这是 API 的当前输出:
enter image description here
仅出于测试目的,我想在响应前后添加 HTML 标记:
类似于(在 DOM 中手动编辑):
enter image description here
所以我添加了这个:
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(); });
}
但是当我运行它时,我得到:

fail:Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware1An unhandled exception has occurred while executing the request. System.InvalidOperationException: Headers are read-only, response hasalready started.With this HTML :


enter image description here
我一直在寻找解决方案,但没有找到,如何去做。
问题:
为什么会发生?我以为我可以通过调用 next() 来控制管道并做任何我想做的事情在管道上。
如何在前后添加自定义 HTML 标签?
编辑:
如果我将代码移到 Configure 的末尾方法,我看到 the regular output ,没有得到异常,但没有 HTML 标签。
编辑 #2:
我也试过 OnStarting event ,但仍然没有成功(我得到一个空页面):
 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();

});

最佳答案

使用以下中间件,我可以在操作结果前后添加 html 标签:

public class BeforeAfterMiddleware
{
private readonly RequestDelegate _next;
public BeforeAfterMiddleware(RequestDelegate next)
{
_next = next;
}

public async Task Invoke(HttpContext context)
{
//Redirect response into a memorystream
using var actionResponse = new MemoryStream();
var httpResponse = context.Response.Body;
context.Response.Body = actionResponse;

//Call the handler action
await _next.Invoke(context);

//Read the handler response from the memory stream
actionResponse.Seek(0, SeekOrigin.Begin);
var reader = new StreamReader(actionResponse);
using var bufferReader = new StreamReader(actionResponse);
string body = await bufferReader.ReadToEndAsync();

//Remove the handler's response from the memory stream
context.Response.Clear();

//Write data to the memorystream
await context.Response.WriteAsync("<h1>HI</h1>");
await context.Response.WriteAsync(body);
await context.Response.WriteAsync("<h1>BYE</h1>");

//Copy memorystream to the response stream
context.Response.Body.Seek(0, SeekOrigin.Begin);
await context.Response.Body.CopyToAsync(httpResponse);
context.Request.Body = httpResponse;
}
}
  • 它只是将响应重定向到 MemoryStream
  • 然后在
  • 之前和之后使用一些文本更改它
  • 最后将 memoryStream 重定向回响应流

  • 用法: app.UseMiddleware<BeforeAfterMiddleware>();

    关于c# - 在asp.net核心响应之前和之后附加自定义HTML输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67554325/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com