ASP>NET Core 2.1:应用程序内的新类实例。地图



我有一个中间件来获取以"proxycall"开头的HTTP请求,并且只获取这些请求。我想我可以在startup.config中的app.map中调用中间件,但问题是我不知道如何实例化它

这是我的程序文件:

public static void Main(string[] args)
{            
CreateWebHostBuilder(args).Build().Run();
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)                
.UseStartup<Startup>()
.ConfigureLogging(logging =>
{
logging.ClearProviders();
logging.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace);
})
.UseNLog();

这是我的启动文件:

public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{            
string connectionString =
Configuration.GetConnectionString("DefaultConnection");
services.AddDbContext<GotMapContext>(o => o.UseSqlServer(connectionString));
services.AddSingleton<ConfigHelper>(c => new ConfigHelper(Configuration));
services.Configure<GeoProxyConfig>(Configuration.GetSection("AppSettings"));
services.AddHttpClient();
services.AddAutoMapper(); 
services.AddMvc()
.AddJsonOptions(o => o.SerializerSettings.ContractResolver = 
new DefaultContractResolver());                 
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseDeveloperExceptionPage();
app.UseStatusCodePages();
app.UseStaticFiles();
app.Map(new PathString("/proxycall"), 
a => a.Run(async(context ) => 
{
// TODO : Create an new instance of GeoProxyMiddleware. 
// The class requires the config, httpclient and logger instance.
}));
app.UseMvcWithDefaultRoute();
}

以下是我尝试从app.map:调用的中间件

public class GeoProxyMiddleware
{
private readonly IOptions<GeoProxyConfig> _geoProxyConfig;
private readonly IHttpClientFactory _httpClientFactory;
private readonly ILogger<GeoProxyMiddleware> _logger;
public GeoProxyMiddleware(
IOptions<GeoProxyConfig> config, 
IHttpClientFactory HttpClientFactory, 
ILogger<GeoProxyMiddleware> logger)
{
_geoProxyConfig = config;
_httpClientFactory = HttpClientFactory;
_logger = logger;
}
}

我在这个链接中找到了问题的答案:https://www.devtrends.co.uk/blog/conditional-middleware-based-on-request-in-asp.net-core

app.MapWhen(context => context.Request.Path.StartsWithSegments("/proxycall"), 
appBuilder => {
appBuilder.UseMiddleware<GeoProxyMiddleware>();
});

相关内容

  • 没有找到相关文章

最新更新