【发布时间】:2019-01-30 07:55:17
【问题描述】:
我已经使用 ResponseWriter 实现了健康检查:
services.AddHealthChecks()
.AddCheck("My Health Check", new MyHealthCheck(aVariable));
app.UseHealthChecks("/health", new HealthCheckOptions()
{
ResponseWriter = WriteHealthCheckResponse
});
private static Task WriteHealthCheckResponse(HttpContext httpContext, HealthReport result){
httpContext.Response.ContentType = "application/json";
var json = new JObject(
new JProperty("status", result.Status.ToString()),
new JProperty("results", new JObject(result.Entries.Select(pair =>
new JProperty(pair.Key, new JObject(
new JProperty("status", pair.Value.Status.ToString()),
new JProperty("description", pair.Value.Description)))))));
return httpContext.Response.WriteAsync(
json.ToString(Formatting.Indented));}
我期待它返回一个 health.json 文件,但它只返回 health。浏览器无法识别没有扩展名的文件,也不想打开它,因此我想控制文件名。
如何控制响应的文件名?
更新:
当健康检查通过时,我现在做得到一个 health.json 文件(可以打开)。 但是,当健康检查失败时,我会得到一个 health 文件。
尝试下载失败 health 消息(不带 .json 扩展名的健康),我只下载了可以打开的部分下载,但保持为空。
那么,这段代码中的不愉快流程有什么问题:
public Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = default(CancellationToken)){
var isHealthy = false;
try
{
var executionResult = _service.ExecuteExample();
isHealthy = executionResult != null;
}
catch
{
//This should not throw an exception.
}
HealthCheckResult healthResult = isHealthy
? HealthCheckResult.Healthy("The service is responding as expected.")
: HealthCheckResult.Unhealthy("There is a problem with the service.");
return Task.FromResult(healthResult);}
【问题讨论】:
-
“当然浏览器无法识别没有扩展名的文件。” - 你的期望是什么? “不认识”是什么意思?您的意思是它不会提示您下载 JSON 响应吗?
-
补充问题:通过控制文件名,浏览器可以识别文件类型,直接打开文件。
-
我的浏览器很乐意为我显示 JSON。确定 Content-Type 标头生效了吗?
-
您只需将 .json 扩展名添加到您的浏览器 URL 中,就可以告诉浏览器会发生什么。这适用于 Chrome
-
您正确地将响应的
Content-Type设置为application/json。浏览器如何处理 JSON 不在您的控制范围内,但它可能会受到 URL(它以.json结尾)的影响,尤其是在扩展映射到应用程序的 Windows 上。但是,文件扩展名 的概念并不是 HTTP 的一部分。话虽如此,您可以使用Content-Disposition 标头指示浏览器使用指定的文件名保存文件。但是,这通常用于下载而不是 JSON 响应。
标签: c# asp.net-core health-monitoring