Не удалось запустить Kestrel, system.InvalidOperationException

У меня проблема с запуском моего веб-API. Я использую .net core 3.0 Web Api. Я без проблем отлаживал и тестировал его локально с помощью iis express. но когда я пытался развернуть веб-api на своем Linux-сервере, я получаю сообщения об ошибках, которые выглядят следующим образом:

крит: Microsoft.AspNetCore.Server.Kestrel [0] Невозможно запустить Kestrel. System.InvalidOperationException: базу пути можно настроить только с помощью IApplicationBuilder.UsePathBase ().

и запуск его на моем локальном компьютере в режиме отладки делает то же самое. поэтому я создал новый профиль для запуска исполняемого файла при отладке приложения в VS.

Возникло исключение: «System.InvalidOperationException» в System.Private.CoreLib.dll Необработанное исключение типа «System.InvalidOperationException» произошло в System.Private.CoreLib.dll. Базу пути можно настроить только с помощью IApplicationBuilder.UsePathBase ().

вот код в Program.cs и Startup.cs

public class Program
{
    public static void Main(string[] args)
    {
        CreateWebHostBuilder(args).Build().Run();
    }

    public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .ConfigureKestrel((a, b) => { })
                .UseUrls("http://*:5050,https://*:5051")
                .UseKestrel()                
                .UseStartup<Startup>();
}
public class Startup

{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc(options => options.EnableEndpointRouting = false).SetCompatibilityVersion(CompatibilityVersion.Version
{
  "iisSettings": {
    "windowsAuthentication": false,
    "anonymousAuthentication": true,
    "iisExpress": {
      "applicationUrl": "http://localhost:60850",
      "sslPort": 44372
    }
  },
  "$schema": "http://json.schemastore.org/launchsettings.json",
  "profiles": {
    "IIS Express": {
      "commandName": "Executable",
      "launchBrowser": true,
      "launchUrl": "api/values",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    },
    "Kestrel": {
      "commandName": "Executable",
      "executablePath": ".\\WebApi.exe",
      "applicationUrl": "http://localhost:5050"
    }
  }
}
0); connectionObject.SetConfiguration(Configuration); // configure strongly typed settings objects var appSettingsSection = Configuration.GetSection("AppSettings"); services.Configure<AppSettings>(appSettingsSection); // configure jwt authentication var appSettings = appSettingsSection.Get<AppSettings>(); var key = Encoding.ASCII.GetBytes(appSettings.Secret); services.AddAuthentication(x => { x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }) .AddJwtBearer(x => { x.Events = new JwtBearerEvents { OnTokenValidated = context => { var userService = context.HttpContext.RequestServices.GetRequiredService<IUserData>(); var userId = int.Parse(context.Principal.Identity.Name); var user = userService.GetById(userId); if (user == null) { // return unauthorized if user no longer exists context.Fail("Unauthorized"); } return Task.CompletedTask; } }; x.RequireHttpsMetadata = false; x.SaveToken = true; x.TokenValidationParameters = new TokenValidationParameters { ValidateIssuerSigningKey = true, IssuerSigningKey = new SymmetricSecurityKey(key), ValidateIssuer = false, ValidateAudience = false }; }); // configure DI for application services services.AddScoped<IUserData, UD>(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } app.UseHttpsRedirection(); app.UseAuthentication(); app.UseMvc(); } }

вот мои настройки запуска

{
  "iisSettings": {
    "windowsAuthentication": false,
    "anonymousAuthentication": true,
    "iisExpress": {
      "applicationUrl": "http://localhost:60850",
      "sslPort": 44372
    }
  },
  "$schema": "http://json.schemastore.org/launchsettings.json",
  "profiles": {
    "IIS Express": {
      "commandName": "Executable",
      "launchBrowser": true,
      "launchUrl": "api/values",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    },
    "Kestrel": {
      "commandName": "Executable",
      "executablePath": ".\\WebApi.exe",
      "applicationUrl": "http://localhost:5050"
    }
  }
}

Я пробовал возиться с

app.UsePathBase("/"); 

or

app.UsePathBase("http://localhost:5050") 

но в последнем случае сообщение об ошибке - это значение, которое должно начинаться с /

Раньше я видел, как другие жалуются на эту проблему, но их решения не помогли мне. почему я вообще это получаю?


person inifus    schedule 02.01.2020    source источник


Ответы (1)


Метод UseUrls(...) ожидает, что URL-адреса будут разделены точкой с запятой ;, а не запятой ,.

Попробуйте изменить строку в program.cs на

.UseUrls("http://*:5050;https://*:5051")

В документации говорится (выделено мной):

Значение, предоставляемое с использованием этих подходов, может быть одной или несколькими конечными точками HTTP и HTTPS (HTTPS, если доступен сертификат по умолчанию). Сконфигурируйте значение как список разделенных точкой с запятой (например, "URL": "http://localhost:8000;http://localhost:8001").

Вы можете увидеть полную документацию здесь

person Simply Ged    schedule 02.01.2020
comment
Спасибо! это решило проблему. Интересно, почему он не может сказать, что не может проанализировать эту строку в UseUrls вместо, казалось бы, несвязанной ошибки. - person inifus; 02.01.2020