无法启动Kestrel,system.InvalidOperationException

时间:2020-01-02 00:38:15

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

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

严重性:Microsoft.AspNetCore.Server.Kestrel [0] 无法启动红est。 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") 

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

开头

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

1 个答案:

答案 0 :(得分:2)

UseUrls(...)方法期望URL用分号;而不是逗号,分隔。

尝试将program.cs中的行更改为

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

文档说(重点是我):

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

您可以查看完整的文档here