【发布时间】:2019-02-28 21:22:24
【问题描述】:
我正在尝试使用中间件将脚本引用注入到由 ASP.NET Core 应用程序生成的所有 HTML 中。我的代码受到this blog 帖子的启发,看起来像这样:
public class MyMiddleware
{
private readonly RequestDelegate _next;
public MyMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext context)
{
var newContent = string.Empty;
var existingBody = context.Response.Body;
using (var newBody = new MemoryStream())
{
context.Response.Body = newBody;
try
{
await _next.Invoke(context);
}
finally
{
context.Response.Body = existingBody;
}
newBody.Seek(0, SeekOrigin.Begin);
newContent = new StreamReader(newBody).ReadToEnd();
if (context.Response.ContentType.StartsWith("text/html"))
{
newContent = newContent.Replace("</body", "<script src=\"my-reference-here\"></script></body");
}
await context.Response.WriteAsync(newContent);
}
}
}
这里的主要挑战是中间件运行对服务器的所有请求,包括 CSS、javascript、favicon 等。我希望它只运行 HTML 输出,因为上面的代码会导致某些文件类型和问题因为我不想把所有的回复都写两次。
有什么更好的方法吗?我已经登录MapWhen,但它似乎不支持查看响应的内容类型。
【问题讨论】:
标签: asp.net-core asp.net-core-middleware