从ASP.NET Core应用程序的根目录返回特定响应

3
我创建了一个ASP.NET Core应用程序,并编写了一些控制器,它们运行良好。路由系统的结构如下:https://something.com/api/controller。但是,我在Azure中使用“始终活动”选项,以保持Web应用程序始终处于活动状态,而不会在空闲时暂停。
问题是,每5分钟,Azure会使用地址https://something.com向我的应用发送请求并返回404错误,这会记录在我的应用程序洞察报告中。
我想知道如何处理对我的应用程序根目录发出的请求并返回200 HTTP结果。
以下是我的启动类:
public class Startup
{
    public Startup(IHostingEnvironment env)
    {
        var builder = new ConfigurationBuilder()
            .SetBasePath(env.ContentRootPath)
            .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
            .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
            .AddEnvironmentVariables();
        Configuration = builder.Build();
    }

    private IConfigurationRoot Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        // Add framework services.
        services.AddMvc();

        services.AddSingleton<ICachingService>(e => new CachingService(Configuration["Redis:ConnectionString"]));

        var loggingService = new LoggingService(Configuration["ApplicationInsights:InstrumentationKey"]);
        services.AddSingleton(typeof(ILoggingService), loggingService);
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        loggerFactory.AddConsole(Configuration.GetSection("Logging"));
        loggerFactory.AddDebug();

        app.UseMvc();
    }
}
3个回答

4
好的,实际上非常简单:
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        app.UseMvc();
        app.Run(async context =>
        {
            await context.Response.WriteAsync("API"); // returns a 200 with "API" as content.
        });
    }

这是一个相当简单的解决方案,它实际上是一个万能路由,如果没有其他匹配项,就会匹配到它。 - juunas
你可能想将其限制在 / 路径下。 - Tratcher

3
app.MapGet("/", () => "Hello Server!");

这适用于 .net 7


你的回答可以通过添加更多关于代码的信息以及它如何帮助提问者来改进。 - Tyler2P
但是代码确切地做了被要求的事。 - Adriano Galesso Alves

3
public void Configure(IApplicationBuilder app)
{
   app.UseEndpoints(endpoints =>
   {
      endpoints.MapGet("/", (context) => context.Response.WriteAsync("Success"));
   });
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接