【问题标题】:Confusion about the WelcomePage middleware using关于 WelcomePage 中间件使用的困惑
【发布时间】:2018-03-19 16:22:57
【问题描述】:

我以以下方式设置了应用程序管道:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.Use(async (context,next) => {

        await context.Response.WriteAsync("Custom MiddleWare");
        await next.Invoke();
    });

    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }

    app.UseWelcomePage(new WelcomePageOptions
    {
        Path = "/Welcome"
    });
    app.Run(async (context) =>
    {
        await context.Response.WriteAsync(Environment.NewLine+"Greetings");
    });
}

当我转到 http://localhost:port/ 页面时,我得到以下输出:

自定义中间件

问候

但是http://localhost:port/welcome 的欢迎页面不起作用并报错:

无法访问此网站

现在,如果我像这样修改管道,它会得到修复:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }

    app.UseWelcomePage(new WelcomePageOptions
    {
        Path = "/Welcome"
    });

    app.Use(async (context, next) => {

        await context.Response.WriteAsync("Custom MiddleWare");
        await next.Invoke();
    });

    app.Run(async (context) =>
    {
        await context.Response.WriteAsync(Environment.NewLine+"Greetings");
    });
}

我试图了解在第一种情况下没有调用 UseWelcomePage 中间件的原因?

【问题讨论】:

    标签: asp.net-core asp.net-core-middleware


    【解决方案1】:

    您的问题是第一个中间件写入响应正文

     await context.Response.WriteAsync("Custom MiddleWare");
    

    这实际上启动了响应,因此 WelcomePage 中间件失败并出现异常,因为无法添加标题,您可能会在日志中看到:

     An unhandled exception has occurred: Headers are read-only, response has already started.
    System.InvalidOperationException: Headers are read-only, response has already started.
       at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.FrameHeaders.ThrowHeadersReadOnlyException()
       at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.FrameHeaders.Microsoft.AspNetCore.Http.IHeaderDictionary.set_Item(String key, StringValues value)
       at Microsoft.AspNetCore.Http.Internal.DefaultHttpResponse.set_ContentType(String value)
       at Microsoft.AspNetCore.Diagnostics.RazorViews.WelcomePage.<ExecuteAsync>d__1.MoveNext()
    --- End of stack trace from previous location where exception was thrown ---
    

    【讨论】:

    • @ExpertNovice: 看起来同样的问题。我添加了 DeveloperExceptionPageMiddleware 并得到了Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware:Error: An unhandled exception has occurred while executing the request
    • 中间件不应写入响应然后调用下一步。这会混淆后续组件,因为它们不能再设置状态码、添加标头等。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-17
    • 2020-03-06
    • 2016-03-16
    • 2013-07-27
    • 1970-01-01
    • 2012-09-20
    相关资源
    最近更新 更多