2017-10-08 272 views
1

我的应用已经管道以下列方式设立WelcomePage中间件:混淆使用

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/我得到下面的输出:

Custom MiddleWare

Greetings

但欢迎页面http://localhost:port/welcome不起作用并出现错误:

This site can’t be reached

现在,如果我修改管道这样它被固定:

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中间件没有得到所谓的在第一个方案的原因是什么?

回答

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 --- 
+0

为什么我的开发者异常页面没有显示出来? –

+0

@ExpertNovice:看起来像是同样的问题。我添加了DeveloperExceptionPageMiddleware并得到了'Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPagePageMiddleware:错误:执行请求时发生了未处理的异常' – Set

+2

中间件不应写入响应,然后再调用。这会混淆后续组件,因为它们不能再设置状态码,添加标题等。 – Tratcher