从startup.cs asp.net核心重定向用户 [英] Redirect user from startup.cs asp.net core

查看:66
本文介绍了从startup.cs asp.net核心重定向用户的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a requirement where I want to check if database is connected(I have the class for that). if this class's method returns false then I want to redirect to database page/view where setup will take place. I have Asp.Net core identity. I want to check this condition before EF core tries to connect to DB. I tried to use the following but returns "too many redirects in browser". Note: Every method in home controller has [Authorize] except DatabaseCheck. Once the user is redirect here I would take values and update Appsettings.json, and application would run normally. Thanks for insights.

    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?}");
            });     




    }

推荐答案

我的建议是使用

My suggestion is to use a Middleware solution that can handle just what you are looking for.

什么是中间件

中间件是组装成 应用程序管道来处理请求和响应.

Middleware is software that is assembled into an application pipeline to handle requests and responses.

每个组件:

选择是否将请求传递给 管道.可以在 管道被调用.

Chooses whether to pass the request to the next component in the pipeline. Can perform work before and after the next component in the pipeline is invoked.

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

Here is a simple implemetation of how the middleware would work.

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

Now as we can assume that only at startup of the application we need to check if the database is installed and not every request to the application we can add the middleware only if it is needed. Therefore on restarts the middleware is only included if the database is not installed. So we will only register the Middleware extension when the database is not installed at startup.

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

The follow code assumes you have reviewed the linked MSDN page above.

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

Here is a simple example of the middleware (I called it 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.

The code is pretty basic, however we see that Invoke method accepts the current HttpContext and injects the IConfiguration instance. Next we run a simple method to check if the database is installed IsDataBaseInstalled.

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

If this method returns false we check to see if the user is currently requesting the databasechecker url. You can change this pattern or add urls as required if there are multiple install urls. If they are not requesting an install URL then we redirect them to the /databasechecker url. Otherwise the Middleware executes as expected with the line await _next(context).

现在要在请求pipleline中使用此功能,只需在之前添加MVC中间件之类的中间件即可.

Now to use this in your request pipleline simply add the middleware before the MVC middleware such as.

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

This is in the startup.cs file. (Below is the basic startup file)

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?}");
    });
}

这篇关于从startup.cs asp.net核心重定向用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆