I am running Visual Studio 2019 which uses IIS Express for Web applications. It was running fine up till suddenly a website I was working on (ASP.NET Core) crashed and gave an error. I went and fixed the error and now all I get is https://localhost:44314 can not be reached (see image 1 below). I have all the routing in the code and even reverted my code to the last working version with still no luck. I have even reinstalled Visual Studio and iisexperess. You can see my startup code below.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace Website
{
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.AddControllersWithViews();
}
// 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.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
}
}
Related
Edit: Used a pre release of a nuget, reverted back to older version and no longer got this error.
I am getting this error (Title), but cannot figure out what is wrong.
App works fine locally, publishes to Azure but gives me HTTP error 500 when trying to open the website.
I guess I might be missing a service in my Startup class?
This is the Startup.cs:
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc.Authorization;
using Microsoft.Identity.Web;
using Microsoft.Identity.Web.UI;
namespace AppOwnsData
{
using AppOwnsData.Models;
using AppOwnsData.Services;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
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)
{
// Get the scopes from the configuration (appsettings.json)
var initialScopes = Configuration.GetValue<string>("DownstreamApi:Scopes")?.Split(' ');
// Add sign-in with Microsoft
services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApp(Configuration.GetSection("AzureAd"))
// Add the possibility of acquiring a token to call a protected web API
.EnableTokenAcquisitionToCallDownstreamApi(initialScopes)
// Enables controllers and pages to get GraphServiceClient by dependency injection
// And use an in memory token cache
.AddMicrosoftGraph(Configuration.GetSection("DownstreamApi"))
.AddDistributedTokenCaches();
// Register AadService and PbiEmbedService for dependency injection
services.AddScoped(typeof(AadService))
.AddScoped(typeof(PbiEmbedService))
.AddScoped(typeof(PowerBiServiceApi));
services.AddControllersWithViews(options =>
{
var policy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
options.Filters.Add(new AuthorizeFilter(policy));
});
// Enables a UI and controller for sign in and sign out.
services.AddRazorPages()
.AddMicrosoftIdentityUI();
// Loading appsettings.json in C# Model classes
services.Configure<AzureAd>(Configuration.GetSection("AzureAd"))
.Configure<PowerBI>(Configuration.GetSection("PowerBI"));
/*// Add the UI support to handle claims challenges
services.AddServerSideBlazor()
.AddMicrosoftIdentityConsentHandler();*/
}
// 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.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
endpoints.MapRazorPages();
});
}
}
}
This is the error I am getting from the call stack in azure application insight:
System.InvalidOperationException: at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService
(Microsoft.Extensions.DependencyInjection.Abstractions,
Version=7.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60)
at
Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService
(Microsoft.Extensions.DependencyInjection.Abstractions,
Version=7.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60)
at
Microsoft.Identity.Web.GraphServiceCollectionExtensions+<>c.b__1_0
(Microsoft.Identity.Web.MicrosoftGraph, Version=2.0.6.0,
Culture=neutral, PublicKeyToken=0a613f4dd989e8ae)
I used a pre release of Microsoft.Identity.Web Nuget that caused this issue. After reverting back to an older version it worked fine.
I saw a few articles about IApplicationLifetime and the way I can trigger execution when application starts and stops but I probably miss something because it is just not triggered.
Here is my workaround:
I opened a project template Container Application for kubernetes, asp.net core 2.2
Program.cs looks as it was created:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
namespace Kubernetes1
{
public class Program
{
public static void Main(string[] args)
{
CreateWebHostBuilder(args).Build().Run();
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>();
}
}
Startup.cs looks as following:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Hosting.Internal;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
namespace Kubernetes1
{
public class Startup
{
// 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)
{
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, IApplicationLifetime appLifetime)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
//var appLifetime = app.ApplicationServices.GetRequiredService<IApplicationLifetime>();
appLifetime.ApplicationStopping.Register(() => Console.WriteLine("ApplicationStopping called"));
appLifetime.ApplicationStopped.Register(() => Console.WriteLine("ApplicationStopped called"));
app.Run(async (context) =>
{
Console.WriteLine("AAA");
});
}
}
}
All I wanted to do here is running the app in cmd, then stop it and see 2 lines printed in console:
ApplicationStopping called
ApplicationStopped called
I didn't manage to make it happen.
Any ideas?
in a different cmd window I type: Get-Process -Name *dotnet* | Stop-Process
Stop-Process will kill the process, skipping any graceful shutdown behavior an application might have.
When the IApplicationLifetime talks about the application stopping, then it refers to the application being gracefully shut down. There are a few ways to trigger this, depending on how the application is starting:
When the application is running in the console: CTRL + C. For example when running through dotnet run or running the compiled executable directly.
When the application is running in IIS: Stopping the website or the application pool.
When the application is running as a Windows Service: Stopping the service.
Recently I have been switching slowly over to .NET CORE 3.1 for everything I do, but when I was trying to port some of my Web Application (Restful API) I ran into issues with Cors.
Code from project running .NET CORE 2.1:
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
options.AddPolicy("AllowAnyOrigin",
builder => builder
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader());
});
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseHsts();
}
app.UseCors("AllowAnyOrigin");
app.UseHttpsRedirection();
app.UseMvc();
}
Code from project running .NET CORE 3.1:
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddCors(options =>
{
options.AddPolicy("AllowAnyOrigin",
builder => builder
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader());
});
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();
}
else
{
app.UseHsts();
}
app.UseCors("AllowAnyOrigin");
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
When I make a request to the API running 2.1 everything goes as expected, but if I try to make the same request to the API running 3.1 I get a 405 error (Method Not Allowed Error).
Has anyone else run into this issue, if so what is the solution to it?
In your configure method, move:
app.UseCors("AllowAnyOrigin");
in between the
app.UseRouting();
and
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
There is a warning in the documentation that states the cors middleware must be configured between these two methods or the middleware will stop functioning.
https://learn.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-3.1
See section labeled "Apply CORS policies to all endpoints"
Configuring the components in the pipeline is both awesome as it give you control but a huge pain because of ordering constraints, I'm personally waiting for someone to create a VS add-on that will analyze these and throw warnings. Would be a great project if someone was so inclined.
I created a project on Visual Studio Code on Mac and wanted to set my default page. I wrote the code on the "Startup.cs", but it's not working.
When I run the project and open the browser it shows that is not finding the controller.
Follow the Startup.cs code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace ProblemsV4
{
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();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Problem}/{action=Index}");
});
}
}
}
You should create a MVC project to be able to define the initial URL.
Your problem is because you're creating a Web API project instead of a MVC project,
because it's an API, doesn't make sense to have a default initial url, like MVC project (because of the views),
You could follow this tutorial to create a MVC application and set the default controller:
https://learn.microsoft.com/en-us/aspnet/core/tutorials/first-mvc-app-xplat/
If you mean the page that should open when you click run:
Right click on your project -> properties -> Debug -> Launch browser
I created a new empty Project in Visual Studio 2015 - Update 1 with ASP.NET 5, MVC6 and AngularJS. I want to see the standard error pages when there are errors like 404, 502 etc like shown in the example below.
How can I include those error messages?
At this time I can only look in my browser console and see the 404 errors.
The routing will be client side with the angular ui-router module (if this information is needed here).
Here you can see my startup.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Diagnostics;
using Microsoft.AspNet.Diagnostics.Entity;
using Microsoft.AspNet.Hosting;
using Microsoft.AspNet.Http;
using Microsoft.Extensions.DependencyInjection;
namespace Chronicus
{
public class Startup
{
// 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 http://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app)
{
/*
// auto generated code
app.UseIISPlatformHandler();
app.Run(async (context) =>
{
await context.Response.WriteAsync("Hello World!");
});
*/
app.UseIISPlatformHandler();
app.UseDefaultFiles();
app.UseStaticFiles();
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
app.UseMvc();
}
// Entry point for the application.
public static void Main(string[] args) => WebApplication.Run<Startup>(args);
}
}