使用

时间:2017-10-08 09:58:31

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

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

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中间件的原因?

1 个答案:

答案 0 :(得分:2)

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

 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 ---
相关问题