在启动时重定向 MVC6 应用程序
Redirect MVC6 application on startup
我很想知道在未配置 Web 应用程序的情况下是否完全可以重定向用户。
最初我认为这可以在 start.cs 文件中的 Configure 方法中完成,但有人告诉我这可能是不可能的。
目前我正在检查我的登录控制器中的配置状态,但对我来说这似乎很草率,因此我正在寻找更好的解决方案,但我总是一片空白。也就是说最好的方法是什么?
您可以尝试在管道的开头添加一些中间件。 (您可以查看 the middleware section of the asp docs for an overview. This post 在 ASP 5 中也有关于新中间件功能的非常好的概述。
一种简单的方法是在注册 MVC 管道之前将其添加为内联中间件。更新Startup.cs的Configure
方法为:
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
app.Use(async (context, next) =>
{
if (!YourWayOfCheckingIfAppIsConfigured())
{
//redirect to another location if not ready
context.Response.Redirect("/Home/NotReady");
return;
}
//app is ready, invoke next component in the pipeline (MVC)
await next.Invoke(context);
});
... configure MVC
如果你需要更复杂的逻辑,你可以将它封装在你自己的中间件class中(参见Writing middleware in the asp docs or Middleware as a standalone class部分)并在Configure
的开头注册它方法:
app.UseMiddleware<MyWaitForAppStartupMiddleware>();
我很想知道在未配置 Web 应用程序的情况下是否完全可以重定向用户。
最初我认为这可以在 start.cs 文件中的 Configure 方法中完成,但有人告诉我这可能是不可能的。
目前我正在检查我的登录控制器中的配置状态,但对我来说这似乎很草率,因此我正在寻找更好的解决方案,但我总是一片空白。也就是说最好的方法是什么?
您可以尝试在管道的开头添加一些中间件。 (您可以查看 the middleware section of the asp docs for an overview. This post 在 ASP 5 中也有关于新中间件功能的非常好的概述。
一种简单的方法是在注册 MVC 管道之前将其添加为内联中间件。更新Startup.cs的Configure
方法为:
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
app.Use(async (context, next) =>
{
if (!YourWayOfCheckingIfAppIsConfigured())
{
//redirect to another location if not ready
context.Response.Redirect("/Home/NotReady");
return;
}
//app is ready, invoke next component in the pipeline (MVC)
await next.Invoke(context);
});
... configure MVC
如果你需要更复杂的逻辑,你可以将它封装在你自己的中间件class中(参见Writing middleware in the asp docs or Middleware as a standalone class部分)并在Configure
的开头注册它方法:
app.UseMiddleware<MyWaitForAppStartupMiddleware>();