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

I'm building a brand new ASP.Net Core MVC project. When I try to run it in the debugger, I get this error:
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.
The error occurs in my 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>();
});
}
I found this SO post getting a similar issue, however my problem is not that the address is already in use, and I am not on a mac. I have updated to the most recent VS version, 17.1.0 at time of writing, but the error persists.
Can anyone offer advice?
EDIT: I tried using the localhost port numbers that were assigned to the application at create time, 7161 and 5161, and I get the same error: "SocketException: An invalid argument was supplied."
I've also tried opening the port in Windows Firewall. No change.
EDIT 2: Here's the code in Startup.cs as well.
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?}");
});
}
}

See https://stackoverflow.com/a/70915818/13242440
In the command line, on behalf of the administrator:
net stop winnat
net start winnat

So this makes absolutely no sense, but I was able to get it working by setting the debugger to use "IIS Express", instead of the project name. It's the dropdown next to the green "play" button in VS; not sure what that setting's called.
Anyway, that fixed it for me.

Related

AuthenticateResult.Principal is null when trying to authenticate with Google

I'm trying to allow users to log in with their Google account on my ASP.NET Core Blazor app. Whenever I go to my app/login/google-login, everything works as expected. I get redirected to google's login page and I get to choose an account to log in with. After choosing my account, it takes a few seconds to load and then visual studio 2019 tells me this:
System.NullReferenceException: 'Object reference not set to an instance of an object.' Microsoft.AspNetCore.Authentication.AuthenticateResult.Principal.get returned null.
at this block of code:
var claims = response.Principal.Identities.FirstOrDefault().Claims.Select(claim => new
{
claim.Issuer,
claim.OriginalIssuer,
claim.Type,
claim.Value
});
Some debugging has revealed the following:
{"succeeded":false,"ticket":null,"principal":null,"properties":null,"failure":null,"none":true}
This is the response I get from Google's API formatted as JSON. Basically it tells me that the principal is null, which I could have guessed, but the rest is also null. What's going on here? Could this simply be an issue with my scopes on Google's end? I have reasons to believe this isn't the problem though since my app should be able to work with any API response without crashing, right?
Here's my LoginController.cs class:
[AllowAnonymous, Route("login")]
public class LoginController : Controller
{
[Route("google-login")]
public IActionResult GoogleLogin()
{
var properties = new AuthenticationProperties { RedirectUri = Url.Action("GoogleResponse") };
return Challenge(properties, GoogleDefaults.AuthenticationScheme);
}
[Route("google-response")]
public async Task<IActionResult> GoogleResponse()
{
var response = await HttpContext.AuthenticateAsync(CookieAuthenticationDefaults.AuthenticationScheme);
var claims = response.Principal.Identities.FirstOrDefault().Claims.Select(claim => new
{
claim.Issuer,
claim.OriginalIssuer,
claim.Type,
claim.Value
});
return Json(claims);
}
}
Here's my 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.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
services.AddRazorPages();
services.AddServerSideBlazor();
//services.AddSingleton<WeatherForecastService>();
services.AddDbContext<Context>(options => options.UseSqlServer(Configuration.GetConnectionString("Context")));
services.AddIdentity<User, Role>().AddEntityFrameworkStores<Context>();
services.AddHttpContextAccessor();
services.AddScoped<IReservationService, ReservationService>();
services.AddAuthentication(options =>
{
options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
})
.AddCookie(options =>
{
options.LoginPath = "/login/google-login";
})
.AddGoogle(options =>
{
options.ClientId = Configuration["Google:ClientID"];
options.ClientSecret = Configuration["Google:ClientSecret"];
});
}
// 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("/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.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
endpoints.MapBlazorHub();
endpoints.MapFallbackToPage("/_Host");
});
}
}
If you need any additional info or code, I'll be happy to provide that ASAP.
This line, that is arguably a fairly big part of my project, was preventing communication with Google for who knows what reason.
services.AddIdentity<User, Role>().AddEntityFrameworkStores<Context>();
I now basically just went on without UserManager and RoleManager and just wrote manual methods for accessing AspNetUsers etc.
Probably not a real solution but it is what it is.

Asp.net core 3 Identity server 4 application crash Stack Overflow

I have an Identity server 4 using Asp.net core. The application crash after browsing. I am using the CMD to run the application
macbooks-MacBook-Air:Falcon-Identity macbook$ dotnet run
[20:52:42 Information]
Starting host...
info: IdentityServer4.Startup[0]
Starting IdentityServer4 version 4.0.0+1acafade44176bf817412aa4309d5dff6587a741
info: IdentityServer4.Startup[0]
You are using the in-memory version of the persisted grant store. This will store consent decisions, authorization codes, refresh and reference tokens in memory only. If you are using any of those features in production, you want to switch to a different store implementation.
info: IdentityServer4.Startup[0]
Using the default authentication scheme Identity.Application for IdentityServer
info: Microsoft.Hosting.Lifetime[0]
Now listening on: https://localhost:5001
info: Microsoft.Hosting.Lifetime[0]
Now listening on: http://localhost:5000
info: Microsoft.Hosting.Lifetime[0]
Application started. Press Ctrl+C to shut down.
info: Microsoft.Hosting.Lifetime[0]
Hosting environment: Development
info: Microsoft.Hosting.Lifetime[0]
Content root path: /Users/macbook/Projects/Falcon-Identity/Falcon-Identity
Stack overflow.
macbooks-MacBook-Air:Falcon-Identity macbook$
When I am browsing the URL https://localhost:5001 Keep getting the stack overflow error, but don't know what's causing the issue.
Startup.CS
public class Startup
{
public IConfigurationRoot Configuration { get; }
public IWebHostEnvironment Environment { get; }
public Startup(IWebHostEnvironment environment)
{
Environment = environment;
var builder = new ConfigurationBuilder()
.SetBasePath(Environment.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddEnvironmentVariables();
Configuration = builder.Build();
}
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
services.AddIdentityServer(Configuration);
services.ConfigureCors();
services.ConfigureExternalOidcProvider();
services.AddAutoMapper(typeof(Startup));
services.AddTransient<EmailHelper>();
services.AddTransient<ITemplateHelper, TemplateHelper>();
services.SwaggerConfig();
services.ConfigureGlobalExceptionFilter();
// In production, the React files will be served from this directory
services.AddSpaStaticFiles(configuration => { configuration.RootPath = "ClientApp/build"; });
services.AddControllersWithViews().AddRazorRuntimeCompilation();
}
// 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("/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.ConfigureCsp();
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseSpaStaticFiles();
app.UseIdentityServer();
app.UseMongoDbForIdentityServer();
// Enable middleware to serve generated Swagger as a JSON endpoint.
app.UseSwagger();
// Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.),
// specifying the Swagger JSON endpoint.
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
});
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller}/{action=Index}/{id?}");
});
app.UseSpa(spa =>
{
spa.Options.SourcePath = "ClientApp";
if (env.IsDevelopment())
{
spa.UseReactDevelopmentServer(npmScript: "start");
}
});
}
}
Might be the same problem I had.
Microsoft.AspNetCore.Identity is calling SignInManager.SignOutAsync when the session cookie expires or is invalid which gets picked up by the Identity Server to log the user out on all the clients the user is logged in. If the cookie is invalid, then you are not authenticated, and the Identity Server tries to authenticat you in order to get the list of clients you are logged in and you end up with this stack overflow.
How can you fix this?
As a dirty quick fix, you can add a class that looks like this:
public class FixedDefaultUserSession : IdentityServer4.Services.DefaultUserSession
{
bool _authenticateAsyncRunning = false;
public NewDefaultUserSession(IHttpContextAccessor httpContextAccessor, IAuthenticationHandlerProvider handlers, IdentityServerOptions options, ISystemClock clock, ILogger<IUserSession> logger)
: base(httpContextAccessor, handlers, options, clock, logger)
{
}
protected override Task AuthenticateAsync()
{
if (_authenticateAsyncRunning)
return Task.CompletedTask;
try
{
_authenticateAsyncRunning = true;
return base.AuthenticateAsync();
}
finally
{
_authenticateAsyncRunning = false;
}
}
}
And register this instead of the DefaultUserSession service in the ConfigureServices like this:
services.RemoveAll<IdentityServer4.Services.IUserSession>();
services.AddScoped<IdentityServer4.Services.IUserSession, FixedDefaultUserSession>();
After that it should at least work.
But I think this issue will be fixed in v4.0.5 or later.
See this issue: https://github.com/IdentityServer/IdentityServer4/issues/4844

HTTP Error 500.30 - ANCM In-Process Start Failure .NET Core

I am using .NET Core 3.0 and suddenly I am getting error below, yes it was working fine last week:-
Nonetheless something has changed and I can't workout what - seems to be related to a directory being wrong.
I have deleted the .vs hoping it would work after it is regenerated...
I have followed below links but to no avail...
HTTP Error 500.30 - ANCM In-Process Start Failure
Reading and using appsettings.json in Program.cs?
https://forums.asp.net/t/2159371.aspx?Application+LM+W3SVC+10+ROOT+failed+to+start+process+ErrorCode+0x80070005+
Dotnet Core Multiple Startup Classes with In-Process Hosting
The Event Viewer shows:-
Adding 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.AddMvc();
services.AddAuthorization(options =>
{
options.AddPolicy("ADGroup", policy =>
policy.Requirements.Add(new UserHelper.CheckAdGroupRequirement(Configuration["SecuritySettings:ADGroup"])));
});
services.AddSingleton<IAuthorizationHandler, UserHelper.CheckAdGroupHandler>();
services.AddHttpContextAccessor();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public static void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error/{0}");
// 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.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
}
A nudge in the right direction would be highly appreciated....

CORS Headers missing from basic API response apnetnet core 3.0

I have just created a default dotnet core 3.0 API project with the basic weather forecast API. I wanted to get CORS working before I did anything else with the project.
In startup i have the following code....
private readonly string MyAllowSpecificOrigins = "_myAllowSpecificOrigins";
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
options.AddPolicy(MyAllowSpecificOrigins,
builder =>
{
builder.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod();
});
});
services.AddControllers();
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
}
// 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();
}
app.UseCors(MyAllowSpecificOrigins);
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
As you can see, I am not doing anything special or seemingly incorrect. This is directly from the MSDN documentation....
https://learn.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-3.0
The problem is that when sending requests through both the browser and postman, There are none of the expected headers in the given responses.
I have googled the crap out of this and have not got anywhere. Am i missing something? could it be environmental? has it changed from a previous version of core?

AddIdentity must be called on the service collection

i have a problem running my Asp.net core site on Debian 8 using netcore 1.1.1 with version 1.0.3
So i made a site using Asp.net core on my windows 10 platform using VS2017 and published it by dotnet publish -c release
Then i uploaded my project using FTP to Debian 8 and then i wrote
dotnet Altram.Web.Donate.dll
Unhandled Exception: System.InvalidOperationException: AddIdentity must be called on the service collection.
at Microsoft.AspNetCore.Builder.BuilderExtensions.UseIdentity(IApplicationBuilder app)
at Altram.Web.Donate.Startup.Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) in /mnt/d/Development/C#/Visual Studio/Altram System/Altram.Web.Donate/Startup.cs:line 104
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at Microsoft.AspNetCore.Hosting.ConventionBasedStartup.Configure(IApplicationBuilder app)
at Microsoft.AspNetCore.Hosting.Internal.WebHost.BuildApplication()
at Microsoft.AspNetCore.Hosting.WebHostBuilder.Build()
at Altram.Web.Donate.Program.Main(String[] args) in /mnt/d/Development/C#/Visual Studio/Altram System/Altram.Web.Donate/Program.cs:line 10
Aborted
in Startup.cs at ConfigureServices method i have
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
if (Environment.IsDevelopment())
{
services.AddSwaggerGen(options =>
{
options.SwaggerDoc("v1", new Info());
options.IncludeXmlComments(Path.Combine(PlatformServices.Default.Application.ApplicationBasePath,
"Altram.Web.Donate.xml"));
});
services.AddDbContext<DatabaseContext>(builder =>
{
builder.UseNpgsql(Configuration["Data:AltramDatabase"],
options => options.MigrationsAssembly("Altram.Web.Donate"));
});
services.AddDbContext<DatabaseContextCache>(builder =>
builder.UseInMemoryDatabase());
services.AddIdentity<User, IdentityRole>()
.AddEntityFrameworkStores<DatabaseContext>()
.AddErrorDescriber<ErrorDescriber>()
.AddDefaultTokenProviders();
services.Configure<IdentityOptions>(options =>
{
options.Password.RequiredLength = 46;
});
services.AddMvc();
services.AddDataInitializer();
services.DomainInitializer();
services.Initialize(links =>
{
links.Login = Configuration["Robokassa:RobokassaLogin"];
links.Mode = Configuration["Robokassa:RobokassaMode"];
links.Pass1 = Configuration["Robokassa:RobokassaPass1"];
links.Pass2 = Configuration["Robokassa:RobokassaPass2"];
});
services.AddLogging();
}
}
and Configure Method
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
app.UseBrowserLink();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
app.UseIdentity();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
So it give me that error at app.UseIdentity(); Line
and it's working very good without any problems on Windows 10.
I use PostgresSql with my project.
How can i fix this problem?
I have fixed my error by removing and put it outside of the if brackets
services.AddIdentity<User, IdentityRole>()
.AddEntityFrameworkStores<DatabaseContext>()
.AddErrorDescriber<ErrorDescriber>()
.AddDefaultTokenProviders();
From the if(Enviroment.IsDevelopment()) code because when i start dotnet from the terminal it starts at production Enviroment mode, so addIdentity won't work.

Categories