我有以下代码:
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().AddMvcOptions(options =>
{
options.Filters.Add(new MessageAttribute("This is the Globally-Scoped Filter"));
});
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseMvcWithDefaultRoute();
}
}
public class MessageAttribute : ResultFilterAttribute
{
private string message;
public MessageAttribute(string msg)
{
message = msg;
}
public override void OnResultExecuting(ResultExecutingContext context)
{
WriteMessage(context, $"<div>Before Result:{message}</div>");
}
public override void OnResultExecuted(ResultExecutedContext context)
{
WriteMessage(context, $"<div>After Result:{message}</div>");
}
private void WriteMessage(FilterContext context, string msg)
{
var bytes = Encoding.ASCII.GetBytes($"<div>{msg}</div>");
context.HttpContext.Response.Body.Write(bytes, 0, bytes.Length);
}
}
[Message("This is the Controller-Scoped Filter", Order = 10)]
public class HomeController : Controller
{
[Message("This is the First Action-Scoped Filter", Order = 1)]
[Message("This is the Second Action-Scoped Filter", Order = -1)]
public ViewResult Index()
{
return View("Message", $"This is the {nameof(Index)} action on the {nameof(HomeController)}");
}
}当我点击Index()动作方法时。我得到了以下三个输出中的一个:
1)
Before Result:This is the Second Action-Scoped Filter
Before Result:This is the Globally-Scoped Filter
Before Result:This is the First Action-Scoped Filter
Before Result:This is the Controller-Scoped Filter
After Result:This is the Controller-Scoped Filter
After Result:This is the First Action-Scoped Filter
After Result:This is the Globally-Scoped Filter
After Result:This is the Second Action-Scoped FilterBefore Result:This is the Second Action-Scoped Filter
Before Result:This is the Globally-Scoped Filter
Before Result:This is the First Action-Scoped Filter
Before Result:This is the Controller-Scoped Filter空白页
当页面加载时,通常是2),但有时是3)。刷新后,它有时会给我1),但是不断刷新页面会给我带来随机的结果,更倾向于2)和3)。
如果我在WriteMessage()中放置一个断点,让它中断,然后继续执行,它就会给出预期的输出。
为什么会发生这种不一致的行为呢?
发布于 2020-09-05 11:35:23
Adam是Pro ASP.NET Core 2的作者,我从那里获得了代码片段:
在
2.0中,直到管道中的所有组件都处理了请求之后,才会编写响应。在2.1中,这种情况发生了变化,以便在生成内容后立即编写响应。当您尝试添加到主体时,ASP.NET核心会感到困惑,因为它需要更新内容长度标题,但不能更新,因为响应已经被写入了。
出现不一致的结果是因为您已经创建了一个竞赛条件。有时,在分配线程来写出响应之前,过滤器会修改响应,有时则不会。您可以使用书中指定的ASP.NET核心版本,也可以更新您的代码,这样它就不会在action方法呈现其视图后尝试修改响应。
https://stackoverflow.com/questions/63741546
复制相似问题