无法绑定到 LocalHost(无效异常)错误 Visual Studio 2022

Failed to bind to LocalHost (invalid exception) error Visual Studio 2022

我正在构建一个全新的 ASP.Net Core MVC 项目。当我尝试在调试器中 运行 它时,出现此错误:

System.IO.IOException
  HResult=0x80131620
  Message=Failed to bind to address https://localhost:5001.
  Source=Microsoft.AspNetCore.Server.Kestrel.Core
  StackTrace:
   at Microsoft.AspNetCore.Server.Kestrel.Core.LocalhostListenOptions.<BindAsync>d__2.MoveNext()
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.ConfiguredTaskAwaitable.ConfiguredTaskAwaiter.GetResult()

  This exception was originally thrown at this call stack:
    [External Code]

Inner Exception 1:
AggregateException: One or more errors occurred. (An invalid argument was supplied.) (An invalid argument was supplied.)

Inner Exception 2:
SocketException: An invalid argument was supplied.

错误出现在我的Program.cs class:

public class Program
{
    public static void Main(string[] args)
    {
        CreateHostBuilder(args).Build().Run(); //<-- ERROR BREAKS HERE
    }

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup<Startup>();
            });
}

我发现 this SO post 遇到了类似的问题,但我的问题不是该地址已被使用,而且我不在 mac 上。我已经更新到最新的 VS 版本,在撰写本文时为 17.1.0,但错误仍然存​​在。

谁能给点建议?

编辑:我尝试使用在创建时分配给应用程序的本地主机端口号 7161 和 5161,但我得到了同样的错误:“SocketException:提供了无效参数。”

我也试过在 Windows 防火墙中打开端口。没有变化。

编辑 2:这也是 Startup.cs 中的代码。

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.AddHttpClient();

        services.AddControllersWithViews();

        // declare external services and database contexts

        services.AddDistributedMemoryCache();

        services.AddHsts(options =>
        {
            options.Preload = true;
            options.IncludeSubDomains = true;
            options.MaxAge = TimeSpan.FromDays(1);
        });

        // Adds the HTTPS Redirect
        services.AddHttpsRedirection(options =>
        {
            options.RedirectStatusCode = StatusCodes.Status307TemporaryRedirect;
            options.HttpsPort = 5001;
        });

        services.AddSession(options =>
        {
            options.IdleTimeout = TimeSpan.FromMinutes(20);
            options.Cookie.HttpOnly = true;
            options.Cookie.IsEssential = true;
            options.Cookie.Name = "GLEntry.Authentication";
        });

        // Add IHttpContextAccessor
        services.AddHttpContextAccessor();

        services.AddMvc();

        // May need this for application authentication? 
        services.AddAuthentication(IISDefaults.AuthenticationScheme);
    }

    // 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
        {
            app.UseExceptionHandler("/Home/Error");
            // 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.UseStaticFiles();

        app.UseRouting();

        app.UseAuthentication();
        app.UseAuthorization();

        app.UseSession();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllerRoute(
                name: "default",
                pattern: "{controller=Home}/{action=Index}/{id?}");
        });
    }
}

所以这完全没有意义,但我能够通过将调试器设置为使用“IIS Express”而不是项目名称来让它工作。它是 VS 中绿色“播放”按钮旁边的下拉菜单;不确定那个设置叫什么。

无论如何,这对我来说已经解决了。