我使用了如何在ASP中检查user-agent的公认答案。. NET核心运行状况检查调用(MapHealthChecks)?,只有一个不同的要求:
我的应用程序没有使用App服务身份验证和授权。因此,我需要按照文档允许匿名访问healthcheck。
Startup.cs
//other services
services.AddHttpContextAccessor();
services.AddScoped<IAuthorizationHandler, UserAgentAuthorizationHandler>();
services.AddHealthChecks()
.AddCheck<HealthCheckFoo>("health_check_foo")
.AddCheck<HealthCheckBar>("health_check_bar");
//other services.AddAuthorization
services.AddAuthorization(options =>
{
options.AddPolicy("HealthCheckPolicy", builder =>
{
builder.AddRequirements(new UserAgentRequirement("HealthCheck/1.0"));
});
});
//...
app.UseEndpoints(endpoints =>
{
//other endpoints...
endpoints.MapHealthChecks("/health", new HealthCheckOptions { AllowCachingResponses = false })
.RequireAuthorization("HealthCheckPolicy");
.WithMetadata(new AllowAnonymousAttribute());
我的期望是在本地测试时,https://localhost:5001/health返回一个错误。
看起来你的启动类在endpoints.MapHealthChecks
上有一个错误,添加了RequireAuthorization
,但同时你也添加了AllowAnonymousAttribute
。
试一试:
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
endpoints.MapHealthChecks("/health", new HealthCheckOptions()
{
AllowCachingResponses = false,
})
.RequireAuthorization("HealthCheckPolicy");
});