如何对 ASP.NET/blazor 中的 POST url 进行健康检查

发布于 2025-01-14 13:55:41 字数 3089 浏览 2 评论 0原文

我正在尝试在我的 blazor 应用程序中实施健康检查。为此,我使用了 Microsoft.AspNetCore.Diagnostics.HealthChecks 包等。下面您可以看到 sql 和 url 健康检查。

startup.cs

//using AjuaBlazorServerApp.Data;
using HealthChecks.UI.Client;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Diagnostics.HealthChecks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Diagnostics.HealthChecks;
using Microsoft.Extensions.Hosting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace AjuaBlazorServerApp
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddRazorPages();
            services.AddServerSideBlazor();
            services.AddHostedService<PeriodicExecutor>();
            services.AddHealthChecks().AddUrlGroup(new Uri("https://api.example.com/post"),
                name: "Example Endpoint",
                failureStatus: HealthStatus.Degraded)
            .AddSqlServer(Configuration["sqlString"],
                healthQuery: "select 1",
                failureStatus: HealthStatus.Degraded,
                name: "SQL Server");
            services.AddHealthChecksUI(opt =>
            {
                opt.SetEvaluationTimeInSeconds(5); //time in seconds between check    
                opt.MaximumHistoryEntriesPerEndpoint(60); //maximum history of checks    
                opt.SetApiMaxActiveRequests(1); //api requests concurrency    
                opt.AddHealthCheckEndpoint("Ajua API", "/api/health"); //map health check api    
            }).AddInMemoryStorage();
        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Error");
            }

            app.UseStaticFiles();

            app.UseRouting();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapBlazorHub();
                endpoints.MapFallbackToPage("/_Host");
                endpoints.MapHealthChecks("/api/health", new HealthCheckOptions()
                {
                    Predicate = _ => true,
                    ResponseWriter = UIResponseWriter.
                    WriteHealthCheckUIResponse
                });
                endpoints.MapHealthChecksUI();
            });
        }
    }
}

sql 运行得很好。但是,url 运行状况检查返回以下错误:

Discover endpoint #0 is not responding with code in 200...299 range, the current status is MethodNotAllowed.

我想知道是否有一种方法可以设置方法类型,以及是否需要将一些测试详细信息发送到端点,以便我们实际上可以获得有效的响应。

I am trying to implement health checks in my blazor application. To do so, I have used the Microsoft.AspNetCore.Diagnostics.HealthChecks package among others. Below you can see sql and url health checks.

startup.cs

//using AjuaBlazorServerApp.Data;
using HealthChecks.UI.Client;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Diagnostics.HealthChecks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Diagnostics.HealthChecks;
using Microsoft.Extensions.Hosting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace AjuaBlazorServerApp
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddRazorPages();
            services.AddServerSideBlazor();
            services.AddHostedService<PeriodicExecutor>();
            services.AddHealthChecks().AddUrlGroup(new Uri("https://api.example.com/post"),
                name: "Example Endpoint",
                failureStatus: HealthStatus.Degraded)
            .AddSqlServer(Configuration["sqlString"],
                healthQuery: "select 1",
                failureStatus: HealthStatus.Degraded,
                name: "SQL Server");
            services.AddHealthChecksUI(opt =>
            {
                opt.SetEvaluationTimeInSeconds(5); //time in seconds between check    
                opt.MaximumHistoryEntriesPerEndpoint(60); //maximum history of checks    
                opt.SetApiMaxActiveRequests(1); //api requests concurrency    
                opt.AddHealthCheckEndpoint("Ajua API", "/api/health"); //map health check api    
            }).AddInMemoryStorage();
        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Error");
            }

            app.UseStaticFiles();

            app.UseRouting();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapBlazorHub();
                endpoints.MapFallbackToPage("/_Host");
                endpoints.MapHealthChecks("/api/health", new HealthCheckOptions()
                {
                    Predicate = _ => true,
                    ResponseWriter = UIResponseWriter.
                    WriteHealthCheckUIResponse
                });
                endpoints.MapHealthChecksUI();
            });
        }
    }
}

The sql one works perfectly. However the url health check returns the following error:

Discover endpoint #0 is not responding with code in 200...299 range, the current status is MethodNotAllowed.

What i would like to know is if there is a way to maybe set the method type and if need be send some test details to the endpoint so that we can actually get a valid response.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

甜是你 2025-01-21 13:55:41

AddUrlGroup 具有重载 允许您通过 httpMethod 参数指定方法。尝试使用:

.AddUrlGroup(new Uri("https://api.example.com/post"),
            httpMethod: HttpMethod.Post,
            name: "Example Endpoint",
            failureStatus: HealthStatus.Degraded)

另一个重载 允许显式配置 HttpClient 和 HttpMessageHandler,以添加特定的默认标头,例如,启用压缩或重定向。

.AddUrlGroup(new Uri("https://api.example.com/post"),
            httpMethod: HttpMethod.Post,
            name: "Example Endpoint",
            configureClient: client => {
                client.DefaultRequest.Headers.IfModifiedSince=
                                DateTimeOffset.Now.AddMinutes(-10);
            },
            failureStatus: HealthStatus.Degraded)

又一个重载< /a> 允许显式配置 UriHealthCheckOptions 类生成其他 AddUrlGroup 重载:

.AddUrlGroup(uriOptions=>{
    uriOptions
        .UsePost()
        .AddUri(someUrl,setup=>{
            setup.AddCustomHeader("...","...");
    });
});

无法指定内容标头,因为运行状况检查代码 不发送正文。

AddUrlGroup has an overload that allows you to specify the method through the httpMethod parameter. Try using :

.AddUrlGroup(new Uri("https://api.example.com/post"),
            httpMethod: HttpMethod.Post,
            name: "Example Endpoint",
            failureStatus: HealthStatus.Degraded)

Another overload allows configuring the HttpClient and HttpMessageHandler explicitly, to add specific default headers for example, enable compression or redirection.

.AddUrlGroup(new Uri("https://api.example.com/post"),
            httpMethod: HttpMethod.Post,
            name: "Example Endpoint",
            configureClient: client => {
                client.DefaultRequest.Headers.IfModifiedSince=
                                DateTimeOffset.Now.AddMinutes(-10);
            },
            failureStatus: HealthStatus.Degraded)

Yet another overload allows explicitly configuring the UriHealthCheckOptions class generated by other AddUrlGroup overloads:

.AddUrlGroup(uriOptions=>{
    uriOptions
        .UsePost()
        .AddUri(someUrl,setup=>{
            setup.AddCustomHeader("...","...");
    });
});

There's no way to specify content headers because the health check code doesn't send a body.

女中豪杰 2025-01-21 13:55:41

我接受上面的答案,因为它从技术上回答了我的问题。然而,这是我最终使用的实现。基本上,您必须创建自己的自定义健康检查。

  1. 在项目主目录下添加一个新文件夹并相应命名
    输入图片此处描述

2. 在该文件夹中创建一个新类,并添加类似于下面的代码

EndpointHealth.cs

using Microsoft.Extensions.Diagnostics.HealthChecks;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using System.Net;
using System.IO;
using Microsoft.Extensions.Configuration;

namespace BlazorServerApp.HealthChecks
{
    public class EndpointHealth : IHealthCheck
    {
        public Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken =
         default)
        {
            
                //create a json string of parameters and send it to the endpoint
                var data = new
                {
                    test = "Example",
                };
                string jsonString = JsonSerializer.Serialize(data);
                var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://api.example.com/post");
                httpWebRequest.ContentType = Configuration["application/json"];
                httpWebRequest.Method = Configuration["POST"];
                using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
                {
                    streamWriter.Write(jsonString);
                }
                //Get the endpoint result and use it to return the appropriate health check result
                var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
                if (((int)httpResponse.StatusCode) >= 200 && ((int)httpResponse.StatusCode) < 300)
                return Task.FromResult(HealthCheckResult.Healthy());
                else
                return Task.FromResult(HealthCheckResult.Unhealthy());
        }
    }
}

然后将以下代码添加到startup.cs 文件的顶部<代码>使用BlazorServerApp.HealthChecks;

最后是下面的代码:

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddRazorPages();
            services.AddServerSideBlazor();
            services.AddHealthChecks()
            .AddCheck<EndpointHealth>("Endpoint",null);

        }

I accepted the answer above because it technically answered my question. However, this is the implementation I ended up using. Basically you will have to create your own custom healthcheck.

  1. Add a new folder under you projects main directory and name it accordingly
    enter image description here

2. Create a new class in that folder and add code similar to what I have below

EndpointHealth.cs

using Microsoft.Extensions.Diagnostics.HealthChecks;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using System.Net;
using System.IO;
using Microsoft.Extensions.Configuration;

namespace BlazorServerApp.HealthChecks
{
    public class EndpointHealth : IHealthCheck
    {
        public Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken =
         default)
        {
            
                //create a json string of parameters and send it to the endpoint
                var data = new
                {
                    test = "Example",
                };
                string jsonString = JsonSerializer.Serialize(data);
                var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://api.example.com/post");
                httpWebRequest.ContentType = Configuration["application/json"];
                httpWebRequest.Method = Configuration["POST"];
                using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
                {
                    streamWriter.Write(jsonString);
                }
                //Get the endpoint result and use it to return the appropriate health check result
                var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
                if (((int)httpResponse.StatusCode) >= 200 && ((int)httpResponse.StatusCode) < 300)
                return Task.FromResult(HealthCheckResult.Healthy());
                else
                return Task.FromResult(HealthCheckResult.Unhealthy());
        }
    }
}

Then add the following code to the top of your startup.cs file using BlazorServerApp.HealthChecks;

and finally the below code:

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddRazorPages();
            services.AddServerSideBlazor();
            services.AddHealthChecks()
            .AddCheck<EndpointHealth>("Endpoint",null);

        }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文