繁体   English   中英

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

[英]Return a specific response from the root of an ASP.NET Core app

我创建了一个 ASP.NET Core 应用程序,其中包含一些运行良好的控制器。

路由系统的结构类似于https://something.com/api/controller

但是,我使用 Azure 中的“始终在线”选项来保持 Web 应用程序始终处于活动状态,并且不会在空闲时暂停。

问题是,每隔 5 分钟,Azure 就会使用地址https://something.com ping 我的应用程序,并返回 404 错误,该错误记录在我的 Application Insights 报告中。

我想知道如何处理对我的应用程序根目录发出的请求并返回 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();
    }
}

好吧,它实际上非常简单:

    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.
        });
    }
public void Configure(IApplicationBuilder app)
{
   app.UseEndpoints(endpoints =>
   {
      endpoints.MapGet("/", (context) => context.Response.WriteAsync("Success"));
   });
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM