我正在编写定制中间件,它要求我将结果作为响应头附加到给定的请求. 为此,我创建了如下所示的简单中间件:
public class MyCustomMiddleware
{
private readonly RequestDelegate _next;
public MyCustomMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task InvokeAsync(Microsoft.AspNetCore.Http.HttpContext context, IConfiguration configuration)
{
debug.print("I'm before the next piece of middleware");
await _next(context);
Context.Response.Headers.Add("x-special-header-4", "super secret response header");
}
}
这当然会导致以下例外情况:
Exception thrown: 'System.InvalidOperationException' in Microsoft.AspNetCore.Server.Kestrel.Core.dll System.InvalidOperationException: Headers are read-only, response has already started.
at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpHeaders.ThrowHeadersReadOnlyException() at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpHeaders.System.Collections.Generic.IDictionary<System.String,Microsoft.Extensions.Primitives.StringValues>.Add(String key, StringValues value)
当我使用ActionResult时,也会发生这种情况--但当我请求了根本无法路由的内容时(结果会返回404).
App启动顺序如下所示:
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseMiddleware<MyCustomMiddleware>();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
(我有一个帮助器来设置中间件,我在本文中省略了这一点,但只是添加了定制中间件)
中间件的真正目的是测量花费的时间/其他因素,这将需要我‘完成’请求,然后向响应添加标头-所有这些都不需要修改现有的用户代码.
有没有办法做到这一点?