首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >IResultFilter没有一致的写入响应

IResultFilter没有一致的写入响应
EN

Stack Overflow用户
提问于 2020-09-04 12:50:21
回答 1查看 361关注 0票数 1

我有以下代码:

代码语言:javascript
复制
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)

代码语言:javascript
复制
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 Filter

代码语言:javascript
复制
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

空白页

当页面加载时,通常是2),但有时是3)。刷新后,它有时会给我1),但是不断刷新页面会给我带来随机的结果,更倾向于2)和3)。

如果我在WriteMessage()中放置一个断点,让它中断,然后继续执行,它就会给出预期的输出。

为什么会发生这种不一致的行为呢?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-09-05 11:35:23

Adam是Pro ASP.NET Core 2的作者,我从那里获得了代码片段:

2.0中,直到管道中的所有组件都处理了请求之后,才会编写响应。在2.1中,这种情况发生了变化,以便在生成内容后立即编写响应。当您尝试添加到主体时,ASP.NET核心会感到困惑,因为它需要更新内容长度标题,但不能更新,因为响应已经被写入了。

出现不一致的结果是因为您已经创建了一个竞赛条件。有时,在分配线程来写出响应之前,过滤器会修改响应,有时则不会。您可以使用书中指定的ASP.NET核心版本,也可以更新您的代码,这样它就不会在action方法呈现其视图后尝试修改响应。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63741546

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档