从 startup.cs asp.net core 重定向用户

Raj*_*Raj 2 c# asp.net-mvc asp.net-core

我有一个要求,我想检查数据库是否已连接(我有这方面的课程)。如果此类的方法返回 false,那么我想重定向到将进行设置的数据库页面/视图。我有 Asp.Net 核心身份。我想在 EF 核心尝试连接到数据库之前检查这个条件。我尝试使用以下内容,但返回“浏览器中的重定向过多”。注意:家庭控制器中的每个方法都有 [Authorize],除了 DatabaseCheck。一旦用户被重定向到这里,我将获取值并更新 Appsettings.json,应用程序将正常运行。感谢您的见解。

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddSingleton(Configuration);          

        services.AddDbContext<MyContext>(options =>
        options.UseSqlServer(SqlSettingsProvider.GetSqlConnection()));

        services.AddIdentity<ApplicationUser, IdentityRole>()
            .AddEntityFrameworkStores<MyContext>()
            .AddDefaultTokenProviders();
        services.ConfigureApplicationCookie(options => options.LoginPath = "/Account/LogIn");
        services.AddMvc()
            .AddJsonOptions(options =>
            {
                options.SerializerSettings.Formatting = Formatting.Indented;
            }).AddJsonOptions(options =>
            {
                options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;

            });


    }
      public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {

        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            app.UseBrowserLink();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
        }



        if (!DatabaseInstalledMiddleware.IsDatabaseInstalled(Configuration))
            app.UseMiddleware<DatabaseInstalledMiddleware>();



        app.UseStatusCodePagesWithReExecute("/StatusCodes/{0}");
        app.UseStaticFiles();
        app.UseAuthentication();
        app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
                routes.MapRoute(
                    name: "defaultApi",
                    template: "api/v2/{controller}/{id?}");
            });     




    }
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

Nic*_*ico 6

我的建议是使用可以处理您正在寻找的内容的中间件解决方案。

什么是中间件

中间件是组装到应用程序管道中以处理请求和响应的软件。

每个组件:

选择是否将请求传递给管道中的下一个组件。可以在调用管道中的下一个组件之前和之后执行工作。

这是中间件如何工作的简单实现。

现在我们可以假设,只有在应用程序启动时,我们才需要检查是否安装了数据库,而不是对应用程序的每个请求,我们可以仅在需要时添加中间件。因此,只有在未安装数据库的情况下,才会在重新启动时包含中间件。所以我们只会在启动时没有安装数据库的情况下注册中间件扩展。

以下代码假定您已查看上面链接的 MSDN 页面。

这是中间件的一个简单示例(我称之为DatabaseInstalledMiddleware

public class DatabaseInstalledMiddleware
{
    public DatabaseInstalledMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    readonly RequestDelegate _next;

    public async Task Invoke(HttpContext context, IConfiguration configuration)
    {
        if (!IsDatabaseInstalled(configuration))
        {
            var url = "/databasechecker";
            //check if the current url contains the path of the installation url
            if (context.Request.Path.Value.IndexOf(url, StringComparison.CurrentCultureIgnoreCase) == -1)
            {
                //redirect to another location if not ready
                context.Response.Redirect(url);
                return;
            }
        }
        //or call the next middleware in the request pipeline
        await _next(context);
    }

    public static bool IsDatabaseInstalled(IConfiguration configuration)
    {
        var key = configuration["SQLConnectionSettings:SqlServerIp"];
        return !string.IsNullOrEmpty(key);
    }
}
Run Code Online (Sandbox Code Playgroud)

代码非常基本,但是我们看到该Invoke方法接受当前HttpContext并注入IConfiguration实例。接下来我们运行一个简单的方法来检查是否安装了数据库IsDataBaseInstalled

如果此方法返回,false我们将检查用户当前是否正在请求databasecheckerurl。如果有多个安装 url,您可以根据需要更改此模式或添加 url。如果他们没有请求安装 URL,那么我们会将他们重定向到该/databasecheckerURL。否则,中间件将按预期执行await _next(context)

现在要在您的请求管道中使用它,只需在 MVC 中间件之前添加中间件,例如。

这是在startup.cs文件中。(下面是基本的启动文件)

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
        app.UseBrowserLink();
    }
    else
    {
        app.UseExceptionHandler("/Home/Error");
    }

    app.UseStaticFiles();
    if (!DatabaseInstalledMiddleware.IsDatabaseInstalled(Configuration))
        app.UseMiddleware<DatabaseInstalledMiddleware>();
    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "default",
            template: "{controller=Home}/{action=Index}/{id?}");
    });
}
Run Code Online (Sandbox Code Playgroud)


小智 5

它对我有用!启动.cs

app.Use(async (context, next) =>
{
    await next();
    if (context.Response.StatusCode == 404)
    {
        context.Response.Redirect("/Home/Error404");
        return;
    }
});
Run Code Online (Sandbox Code Playgroud)