Как мне явно указать, какой метод Configure из двух должен вызываться в классе Startup?

using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace ASP_NET_Core_Lessons
{
  public class Startup
  {
    public void ConfigureServices(IServiceCollection services)
    {
    }
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
      if (env.IsDevelopment())
      {
        app.UseDeveloperExceptionPage();
      }
      app.UseRouting();
      app.UseEndpoints(endpoints =>
      {
        endpoints.MapGet("/", async context =>
              {
                await context.Response.WriteAsync("Hello World!");
          });
      });
    }

    IWebHostEnvironment _env;
    public Startup(IWebHostEnvironment env)
    {
      _env = env;
    }
    public void Configure(IApplicationBuilder app)
    {
      app.UseRouting();

      app.UseEndpoints(endpoints =>
      {
        endpoints.MapGet("/", async context =>
        {
          await context.Response.WriteAsync($"Application Name: {_env.ApplicationName}");
        });
      });
    }
  }
}

Как мне явно указать, какой метод Configure из двух должен вызываться?


Ответы (1 шт):

Автор решения: Uranus

Ответ на вопрос можно найти в этом блоге: ASP.NET Core Anatomy – How does UseStartup work? Среди прочего там упоминается такой любопытный момент:

Internally the StartupLoader uses a helper method called FindMethod to do most of the work. <...> This method will first work out the method name(s) it should be looking for on the Startup class based on the methodName parameter passed to it. The convention is that the method which defines the middleware pipeline should be called Configure. There is a lesser known convention in the Startup class which in addition to providing the standard “Configure” method, you can choose to include environment specific version(s) in your Startup class too. By convention, if a Configure{EnvironmentName} is found (e.g. “ConfigureProduction”) for the current environment, that method will be used in preference to the general Configure method.

StartupLoader большую часть работы выполняет с помощью вспомогательного метода FindMethod. <...> Этот метод определяет имя искомого метода на основании переданного параметра methodName. По соглашению, метод который определяет middleware конвейер должен называться Configure. Но существует менее известное соглашение, где помимо метода Configure вы также можете добавить метод привязанный к EnvironmentName. Например, ConfigureProduction.

EnvironmentName определяется переменной окружения ASPNETCORE_ENVIRONMENT: Use multiple environments in ASP.NET Core. Ее необходимо установить на продакшн сервере во время развертывания приложения.

Можно настроить проект таким образом, чтобы во время отладки можно было быстро переключаться между окружениями. Для этого в файле Properties/launchSettings.json должны быть такие записи:

"profiles": {
    "IIS Express": {
        "commandName": "IISExpress",
        "launchBrowser": true,
        "launchUrl": "weatherforecast",
        "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "IIS"
        }
    },
    "Console": {
        "commandName": "Project",
        "launchBrowser": true,
        "launchUrl": "weatherforecast",
        "applicationUrl": "http://localhost:5000",
        "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "DEV"
        }
    }
}

Выбрать необходимое окружение перед запуском приложения в Visual Studio можно прямо в списке под кнопкой Run.

→ Ссылка