具有Dapper和错误处理的Asp Net Core SQL自定义配置提供程序

问题描述 投票:0回答:2

我正在设置我的MVC Web应用程序,以便在启动时从我的SQL Azure数据库中提取配置数据。我已经使用这两篇​​文章(MicrosoftMedium)来指导我,但既不包括错误处理,我想避免任何实体框架引用,因为我正在使用Dapper。到目前为止,我已经使用下面的代码,但我不知道如何处理这种情况下的错误。例如,如果我从SQLConfigurationProvider中的Load方法中删除try / catch,则应用程序在启动时崩溃,但如果我包含try / catch,则会处理错误并且应用程序正常启动但没有配置数据可用,因此最终会崩溃试图访问配置值。优雅地处理这些错误的最佳方法是什么(即app仍然加载但显示错误页面/消息)?拥有SQLConfigurationSource还有什么好处,或者只是在SQLConfigurationProvider中创建新的SqlConnection实例更有意义吗?

Program.cs中

public class Program
{
    public static void Main(string[] args)
    {
        CreateWebHostBuilder(args).Build().Run();
    }

    public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .CaptureStartupErrors(true)
            .UseSetting(WebHostDefaults.DetailedErrorsKey, "true")
            .UseApplicationInsights()
            .ConfigureAppConfiguration((hostingContext, config) =>
            {
                config.AddSQLConfiguration(); // Custom configuration here
            })
            .UseStartup<Startup>();
}

ConfigurationExtensions.cs

public static class ConfigurationExtensions
{
    public static IConfigurationBuilder AddSQLConfiguration(this IConfigurationBuilder builder)
    {
        var connectionString = builder.Build().GetConnectionString("DefaultConnection");
        return builder.Add(new SQLConfigurationSource(connectionString));
    }
}

SQLConfigurationSource.cs

public class SQLConfigurationSource : IConfigurationSource
{
    private readonly SqlConnection _connection;

    public SQLConfigurationSource(string connectionString)
    {
        _connection = new SqlConnection(connectionString);
    }

    public IConfigurationProvider Build(IConfigurationBuilder builder)
    {
        return new SQLConfigurationProvider(_connection);
    }
}

SQLConfigurationProvider.cs

public class SQLConfigurationProvider : ConfigurationProvider
{
    private readonly SqlConnection _connection;

    public SQLConfigurationProvider(SqlConnection connection)
    {
        _connection = connection;
    }

    public override void Load()
    {
        try
        {
            var model = _connection.Query<SQLConfigurationModel>("sp does not exist for example", commandType: CommandType.StoredProcedure);
            Data = model.ToDictionary(x => x.Property, x => x.Value);
        }
        catch (Exception ex)
        {
            // WHAT TO DO HERE?
        }
    }

}

public class SQLConfigurationModel
{
    public string Property { get; set; }
    public string Value { get; set; }
}

----更新:关闭但不是很好----

我添加了异常作为配置值,然后我在Startup.cs的Configure方法中检查,如下所示。这有助于确保应用程序在启动时不会崩溃,但是当我抛出异常时,它不会被路由到错误视图,即使异常处理程序已经配置了app.UseExceptionHandler(“/ Home / Error”)

// Inside SQLConfigurationProvider
public override void Load()
{
    try
    {
        var model = _connection.Query<SQLConfigurationModel>("sp does not exist for example", commandType: CommandType.StoredProcedure);
        Data = model.ToDictionary(x => x.Property, x => x.Value);
    }
    catch (Exception ex)
    {
        Data.Add("ConfigurationLoadException", ex.Message);
    }
}


// Inside Startup.cs
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.UseExceptionHandler("/Home/Error");

    // Check for custom config exception
    string configurationLoadException = Configuration["ConfigurationLoadException"];
    if (configurationLoadException.Length > 0)
    {
        throw new Exception("Configuration Failed: " + configurationLoadException);
    }

    app.UseHttpsRedirection();
    app.UseStaticFiles();
    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "default",
            template: "{controller=Home}/{action=Index}/{id?}");
    });
}
asp.net-core asp.net-core-mvc dapper asp.net-core-2.1
2个回答
1
投票

如果您的应用程序在没有存储在SQL中的配置的情况下无法工作,则应移动此代码以获取数据以便更好地进行错误管理。这样,您将能够向用户显示正确的错误消息并更好地记录它。其他选项是在program.cs中使用try / catch块,并且假设没有SQL驱动配置,不会破坏启动项目,而是在应用程序使用中进一步破坏。如果是这种情况,您将在启动时放置错误管理,它可以为您显示功能错误页面。

This link将为您提供有关startup / program.cs错误处理的一些看法


0
投票

您应该配置自定义错误处理页面请阅读以下内容。这很容易做Custom Error Page .net Core

© www.soinside.com 2019 - 2024. All rights reserved.