【问题标题】:Unable to start Kestrel, system.InvalidOperationException无法启动 Kestrel,system.InvalidOperationException
【发布时间】:2020-04-20 18:13:28
【问题描述】:

我在启动我的 web api 时遇到问题。我正在使用 .net core 3.0 Web Api。 我正在使用 iis express 在本地调试和测试它,没有问题。但是当我尝试将 web api 部署到我的 linux 服务器时,我收到如下所示的错误消息:

暴击:Microsoft.AspNetCore.Server.Kestrel[0] 无法启动 Kestrel。 System.InvalidOperationException:路径基只能使用 IApplicationBuilder.UsePathBase() 配置。

在我的本地机器上以调试模式运行它会做同样的事情。所以我在 VS 中调试应用程序时创建了一个新配置文件来启动可执行文件。

抛出异常:System.Private.CoreLib.dll 中的“System.InvalidOperationException” System.Private.CoreLib.dll 中出现“System.InvalidOperationException”类型的未处理异常 路径基只能使用 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_3_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("/"); 

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

但在后一种情况下,错误消息是值需要以 / 开头

我之前看到过其他人抱怨这个问题,但他们的解决方案对我不起作用。为什么我会得到这个?

【问题讨论】:

    标签: c# .net-core-3.0 kestrel


    【解决方案1】:

    UseUrls(...) 方法要求 URL 用分号 ; 分隔,而不是逗号 ,

    尝试将program.cs中的行改为

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

    文档说(强调我的):

    使用这些方法提供的值可以是一个或多个 HTTP 和 HTTPS 端点(如果默认证书可用,则为 HTTPS)。将值配置为 分号分隔 列表(例如,“Urls”:“http://localhost:8000;http://localhost:8001”)。

    可以查看完整文档here

    【讨论】:

    • 谢谢!那确实解决了问题。我想知道为什么它不能说它无法解析 UseUrls 中的那个字符串,而不是一个看似无关的错误。
    猜你喜欢
    • 2021-02-04
    • 2022-01-07
    • 1970-01-01
    • 2021-12-12
    • 2023-03-23
    • 2019-02-08
    • 2022-12-05
    • 2020-04-30
    • 2022-09-28
    相关资源
    最近更新 更多