简体   繁体   中英

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

I have created an ASP.NET Core app with some controllers which are working fine.

The routing system is structured like https://something.com/api/controller .

However, I am using the Always live option in Azure to keep the web app constantly active and not being paused while idle.

Problem is, every 5 minutes, Azure pings my app with the address https://something.com and comes back with a 404 error which is logged in my Application Insights report.

I would like to know how can I handle the requests made to the root of my app and return a 200 HTTP result instead.

Here is my Startup class:

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();
    }
}

Alright, it is in fact insanely simple:

    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"));
   });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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