【问题标题】:Return a specific response from the root of an ASP.NET Core app从 ASP.NET Core 应用的根目录返回特定响应
【发布时间】:2017-03-04 07:32:49
【问题描述】:

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

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

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

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

我想知道如何处理对我的应用根目录发出的请求并返回 200 HTTP 结果。

这是我的 Startup 课程:

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

【问题讨论】:

    标签: c# asp.net .net asp.net-web-api asp.net-core


    【解决方案1】:

    好吧,其实很简单:

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

    【讨论】:

    • 这是一个非常简单的解决方案,它实际上是一个包罗万象的路线,如果没有其他匹配项,它将匹配。
    • 您可能希望将其限制为 / 路径。
    【解决方案2】:
    public void Configure(IApplicationBuilder app)
    {
       app.UseEndpoints(endpoints =>
       {
          endpoints.MapGet("/", (context) => context.Response.WriteAsync("Success"));
       });
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-24
      • 1970-01-01
      • 2019-04-10
      • 2021-02-10
      相关资源
      最近更新 更多