在使用IdentityServer4时,可以通过添加Access Token的限制方式限制带宽。此外,我们还可以通过应用程序/操作系统/路由器中现有的工具和服务来实现带宽控制。
例如,在基于IIS的应用程序中,我们可以使用IIS的限制带宽设置,在应用程序中添加以下代码:
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
//Add IdentityServer with in-memory user and client stores.
services.AddIdentityServer()
.AddInMemoryClients(config.Clients)
.AddInMemoryIdentityResources(Config.Ids)
.AddInMemoryApiResources(Config.Apis)
.AddInMemoryUsers(config.Users);
//Add a basic http client for api calls
services.AddTransient();
//Add bandwidth limiting
services.AddSingleton();
//Add bandwidth limiter middleware
services.AddTransient();
//Add MVC framework
services.AddMvc();
}
}
然后在middleware中添加以下代码:
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseMiddleware
在上述示例中,我们可以注意到,基于SynchronizedBandwidthLimiter的IBandwidthLimiter被添加到服务容器中. 此外,ProfilerLimiter也被添加到middleware中,以限制带宽。
我们的ProfilerLimiter middleware中的代码如下:
public class ProfilerLimiter { private readonly RequestDelegate _next; private readonly ILogger _logger; private readonly IBandwidthLimiter _limiter;
public ProfilerLimiter(RequestDelegate next, ILogger logger, IBandwidthLimiter limiter)
{
_next = next ?? throw new ArgumentNullException(nameof(next));
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
_limiter = limiter ?? throw new ArgumentNullException(nameof(limiter));
}
public async Task Invoke(HttpContext context)
{
_logger.LogInformation("Profiling bandwidth");
//Limit the bandwidth
await _limiter.LimitBandwidthAsync(context.RequestAborted);
_logger.LogDebug("Bandwidth profiled");
//Call the next middleware
await _next(context);
}
}
上述代码逻辑十分简单,首先我们等待限制带宽,然后LOG一些信息,最后执行下一个middleware。
我们现在使用IIS带宽限制带宽并使用C#实现详细的应用程序配置,其中我们使用SynchronizedBandwidthLimiter限制带宽。
上一篇:半对数坐标回归线