用于设置响应 ContentType 的中间件
我们的想法是使用 HttpContext.Response.OnStarting
回调,因为这是在发送标头之前触发的最后一个事件。将以下内容添加到你的中间件 Invoke
方法中。
public async Task Invoke(HttpContext context)
{
context.Response.OnStarting((state) =>
{
if (context.Response.StatusCode == (int)HttpStatusCode.OK)
{
if (context.Request.Path.Value.EndsWith(".map"))
{
context.Response.ContentType = "application/json";
}
}
return Task.FromResult(0);
}, null);
await nextMiddleware.Invoke(context);
}