从startup.cs asp.net核心重定向用户

问题描述 投票:1回答:1

我有一个要求,我想检查数据库是否已连接(我有类)。如果这个类的方法返回false,那么我想重定向到数据库页面/视图,在那里进行安装。我有Asp.Net核心身份。我想在EF核心尝试连接到DB之前检查这个条件。我尝试使用以下内容但返回“浏览器中的重定向过多”。注意:除了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?}");
            });     




    }

enter image description here

c# asp.net-mvc asp.net-core
1个回答
3
投票

我的建议是使用Middleware解决方案,可以处理您正在寻找的东西。

什么是中间件

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

每个组件:

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

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

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

以下代码假定您已查看上面的链接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);
    }
}

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

如果此方法返回false,我们检查用户当前是否正在请求databasechecker网址。如果有多个安装URL,您可以根据需要更改此模式或添加URL。如果他们没有请求安装URL,那么我们将它们重定向到/databasechecker网址。否则,中间件将使用行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?}");
    });
}
© www.soinside.com 2019 - 2024. All rights reserved.