How to get connection string from appsettings.json inside custom filter in .net core

左心房为你撑大大i 提交于 2020-01-03 04:53:07

问题


I have a controller EBisUserController which contains a public property ConnectionString obtained from appsettings.json through dependency injection. The controller has an attribute filter 'EBisUserAuthResourceFilter' requiring use of the property ConnectionString found in the controller. What is the most performant method to access ConnectionString. I have a working example of what I want, but know this is not the correct way of doing this as it must open and read the file for each transaction.

public class EBisUserAuthResourceFilter : Attribute, IResourceFilter { 

    private string _connectionString;

    public EBisUserAuthResourceFilter() {
        var builder = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("appsettings.json");
        _connectionString= builder.Build().GetValue<string>("Data:DefaultConnection:ConnectionString"); //this property exists as property of controller through DI, how can we access it?
    }
}

回答1:


Dependency injection is possible in filters as well.

Here is a simple way to get connection string

public class EBisUserAuthResourceFilter : Attribute, IResourceFilter
{
    private readonly string connectionString;

    public EBisUserAuthResourceFilter(IConfiguration configuration)
    {
        this.connectionString = configuration
                   .GetSection("ConnectionStrings:DefaultConnection").Value;
    }
    public void OnResourceExecuted(ResourceExecutedContext context)
    {
        // use this.connectionString
    }

    public void OnResourceExecuting(ResourceExecutingContext context)
    {
        // use this.connectionString
    }
}

Now you can use this filter

[ServiceFilter(typeof(EBisUserAuthResourceFilter))]
public class HomeController : Controller
{  }

You also need to add this Filter to the service collection

public void ConfigureServices(IServiceCollection services)
{
   services.AddScoped<EBisUserAuthResourceFilter>();

   // your existing code to add other services
}

Another solution is to have a class representing the structure of the content of AppSettings.json file or a sub section and load that in your Startup classes' ConfigureServices method

services.Configure<SiteSettings>(Configuration);

and now you can inject IOptions<SiteSettings> and use the needed property values. I prefer this as it is less magic strings in my code.



来源:https://stackoverflow.com/questions/47042298/how-to-get-connection-string-from-appsettings-json-inside-custom-filter-in-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!