ASP.NET 5 Template crashes on first run - c#

I'm starting a new project in VS 2015.
File -> New -> Project -> ASP.NET Web Application -> ASP.NET 5 Templates -> Web API
A project is initialized. I would assume that if I run the project with IIS Express a service would be available.
It runs through the startup methods.
public class Startup
{
public Startup(IHostingEnvironment env)
{
// Set up configuration sources.
var builder = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.AddEnvironmentVariables();
Configuration = builder.Build();
}
public IConfigurationRoot Configuration { get; set; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
// Add framework 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, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
app.UseIISPlatformHandler();
app.UseStaticFiles();
app.UseMvc();
}
// Entry point for the application.
public static void Main(string[] args) =>
WebApplication.Run<Startup>(args);
}
}
But then it crashes. I don't know how to implement global error handling.
I looked at this example.
But when I try to use System.Net.Http or System.Web.Http.ExceptionHandling they can't be found.
I also noticed that through intellisense it says Core 5.0 is no available.
Here is my project.json as requested.
{
"version":"1.0.0-*",
"compilationOptions":{
"emitEntryPoint":true
},
"dependencies":{
"Microsoft.AspNet.IISPlatformHandler":"1.0.0-rc1-final",
"Microsoft.AspNet.Mvc":"6.0.0-rc1-final",
"Microsoft.AspNet.Server.Kestrel":"1.0.0-rc1-final",
"Microsoft.AspNet.StaticFiles":"1.0.0-rc1-final",
"Microsoft.Extensions.Configuration.FileProviderExtensions":"1.0.0-rc1-final",
"Microsoft.Extensions.Configuration.Json":"1.0.0-rc1-final",
"Microsoft.Extensions.Logging":"1.0.0-rc1-final",
"Microsoft.Extensions.Logging.Console":"1.0.0-rc1-final",
"Microsoft.Extensions.Logging.Debug":"1.0.0-rc1-final"
},
"commands":{
"web":"Microsoft.AspNet.Server.Kestrel"
},
"frameworks":{
"dnx451":{
"frameworkAssemblies":{
"System.Web":"4.0.0.0"
}
},
"dnxcore50":{
}
},
"exclude":[
"wwwroot",
"node_modules"
],
"publishExclude":[
"**.user",
"**.vspscc"
]
}

Try to open Visual Studio Administrator Mode

I guess it depends on what is crashing - it's not clear from your description what crashes, when it crashes and how it crashes.
You can use UseExceptionHandler and UseDeveloperExceptionPage extension methods to configure an error handling page. This article describes it in more details.
If the exception happens during startup you may need to use UseCaptureStartupErrors extension method (it was recently renamed to CaptureStartupErrors).
Also, you already have logging enabled - the logs may also have some useful information. If you can't see logs because you log to the console consider logging to a file.
If this is IIS/IISExpress crashing check event log.

What is your runtime version ?
Maybe you can try scaffolding your application with the AspNet Yeoman generator and compare the files.
Personally I prefer to use the scaffolder as it is often up to date.
Hope this helps !

Related

How to automatically call a function after pool recycling on IIS

I would like to know-how in my web app written in C#.NET5 (+React) call function after IIS server use setting for recycling Web data on IIS -> Application Pool -> Recycling (Regular Time Interval (In Minutes)) set on 1440.
I load over 6 GB to memory (IMemoryCache) and it takes over 6 minutes then all data is loaded, I would like to call the load function to cache automatically after each cycle of the recycling period, before waiting for the user interaction.
I try it call in StartUp, in Main, and also with use IHostetServices, but in each case, I got an error then called service (my class with load method) is not recognized
3 Ways to Run Code Once at Application Startup in ASP.NET Core
I got these errors: when I try to call
{"Unable to resolve service for type Repository.DataFilters.Static.IGroupLoader' while attempting to activate 'Search.Startup'."}
When I try to call:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseSpaStaticFiles();
// Add other security headers
app.UseMiddleware<SecurityHeadersMiddleware>();
app.UseSerilogRequestLogging();
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller}/{action=Index}/{id?}");
});
app.UseSpa(spa =>
{
spa.Options.SourcePath = "ClientApp";
var isDev = env.EnvironmentName.Contains("Dev");
if (env.IsDevelopment() || isDev)
{
spa.UseReactDevelopmentServer(npmScript: "start");
}
});
_GroupLoader.LoadGroupFiltersToMemory(); // try to call this method from my class
}
In ConfiguredService:
private readonly IGroupLoader _GroupLoader;
public Startup(IConfiguration configuration, IGroupLoader groupLoader)
{
Configuration = configuration;
_GroupLoader = groupLoader;
}
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
services.AddMemoryCache();
// DB Contexts
services.AddDbContext<GroupContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
// Services
services.AddScoped<IGroupService, GroupService>();
// Repositories
services.AddScoped<IGroupLoader, GroupLoader>();
services.AddSpaStaticFiles(configuration =>
{
configuration.RootPath = "ClientApp/build";
});
}
This solution does not work:
<system.webServer>
<aspNetCore xdt:Transform="SetAttributes(startupTimeLimit)" startupTimeLimit="300">
</aspNetCore>
</system.webServer>
After IIS runs Recycling, Its looks like the App is not loaded, I must do an initial run like the open website link, is it possible to load the app automatically after the recycling process of IIS?
In Startup.cs I am not able to call await functions
Called function take over 8 minutes, then all data was loaded
Looks like then I must use: https://learn.microsoft.com/en-us/iis/get-started/whats-new-in-iis-8/iis-80-application-initialization#TOC301259895
Update 09.01.2022
After I set IIS and App to autostart I got this error:
I try to do this:
https://serverfault.com/questions/590865/how-can-i-warm-up-my-asp-net-mvc-webapp-after-an-app-pool-recycle
In web.config I set:
<applicationInitialization
remapManagedRequestsTo="Startup.html"
skipManagedModules="true" >
<add initializationPage="/subpage" />
</applicationInitialization>
Then when I try to call page /subpage (without using Startup.cs ->
Configure call of IMemoryCache function), the function to load into
IMemoryCache is not called, but when I run the app with Visual Studio or
deploy an app to IIS without autostart (warmup), a function is
called.
When I try to call function (with load IMemoryCache) via
Startup.cs -> Configure function, the function is called but IIS server start many (10-11 process) IIS Worker Process and I got
error upper, also Startup.html webpage is not called during the
loading process (I am not sure where must be located in .NET 5
Core Web App with React Solution).
I got this error:
System.InvalidOperationException: Execution Timeout Expired. The timeout period elapsed prior to completion of the operation or the server is not responding.
This was maybe caused by many IIS Worker processes which calls the same function (in IMemoryCache loading function I have use lock())
Thank you
You can't inject your IGroupLoader dependency into your Startup.cs before the depedency injection has been setup - this is described by the error you provided.
According to this guide, you can inject a dependency in Configure once you've setup dependency injection in ConfigureServices.
i.e. you need to change:
from
private readonly IGroupLoader _GroupLoader;
public Startup(IConfiguration configuration, IGroupLoader groupLoader)
{
Configuration = configuration;
_GroupLoader = groupLoader;
}
to
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
from
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
to
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IGroupLoader groupLoader)
from
_GroupLoader.LoadGroupFiltersToMemory();
to
groupLoader.LoadGroupFiltersToMemory();

Asp.Net Core How to Configure Migrations type to assembly

Hello everyone my name is Taniguchi and i learning asp.net core and I managed to create a migration but when I used the Update-Database command show me the following error: "
Specify the '-Verbose' flag to view the SQL statements being applied to the target database.
No migrations configuration type was found in the assembly 'WebApplication1'. (In Visual Studio you can use the Enable-Migrations command from Package Manager Console to add a migrations configuration).
my database:
public class MimicContext : DbContext
{
public MimicContext(DbContextOptions<MimicContext> options) : base(options)
{
}
public DbSet<Palavra> Palavras { get; set; }
}
my startup:
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)
{
services.AddDbContext<MimicContext>(opt =>
{
opt.UseSqlite("Data Source=Database\\Mimic.db");
});
services.AddMvc(options => options.EnableEndpointRouting = false);
}
// 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.UseMvc();
}
}
How can i configure a migration to the assembly ?
Have you enabled migrations in your project? If you didn't than use Enable-Migrations. I think that it could be the problem.
Before running the update command in PMC first enable it. For more details view this link here
Small mistake, but good learning for me after spending more than one day painful effort. I hope this will be the good learning for others too.
I have added two NuGet packages of: EntityFramework, and Microsoft.EntityFrameworkCore which is my mistake.
Just adding NuGet package for Microsoft.EntityFrameworkCore will do all the required work.

Linqpad 6 (Core) and .Net Core Api?

Linqpad 6 supports .Net Core.
When I create a new empty .Net Core API solution in visual studio , I get a simple template with a simple demo controller.
When I run it in visual studio it uses a command-line server (kestrel) to run the project :
So I wanted to see if I can run this project in Linqpad 6.
So I've installed all nugets and copied the code to Linqpad :
https://i.stack.imgur.com/lwRyU.png
void Main()
{
CreateWebHostBuilder(new string[] { "" }).Build().Run();
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>();
[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
[HttpGet]
public ActionResult<IEnumerable<string>> Get()
{
return new string[] { "value1", "value2" };
}
}
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().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}
// 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();
}
app.UseMvc();
}
}
I do see that it is now listening :
But calls to http://localhost:5000/api/values do get acked , but without the json value response from controller :
Question:
How can I get Linqpad to return the value from the controller? ( a simple json)
There's a difference in the way LINQPad executes code that could account for this not working.
Being a scripting tool, LINQPad wraps everything in a class (otherwise, the Main method would have nowhere to live). So ValuesController is actually ends up as a nested type, UserQuery.ValuesController, and this could potentially upset the routing API.
For such situations, LINQPad has the ability to extract all nested types and move them outside UserQuery (using the Roslyn API). To enable this, add the following to the start of your query:
#LINQPad nonest
Something else to consider is that a default MVC project includes an appsettings.json file. Should this be required for your code in LINQPad, you need to create such a file and add a reference to it (when you reference to a non-binary file, LINQPad copies it into the output folder, which is exactly where appsettings.json needs to be).
Edit: There's now a checkbox in the Query Properties dialog to add ASP.NET Core references to a query in LINQPad 6. This pulls the assemblies straight from the shared framework folder, and is easier than finding the right NuGet packages.

Disable application insights in debug

How can I disable application insights automatically when using a debug configuration and enable it only on release?
Is it possible to do this without creating another instrumentation key only for debug?
I have trackevent statements scattered all over the code, enclosing them inside a debug preprocessor check is not an ideal solution.
My current solution is to set the Build Action of the ApplicationInsights.config file to None so that it's not copied to the project's output directory, but this isn't a process that can be automated based on the active build configuration.
There is a Developer Mode but needs to be changed manually (if it was possible to conditionally set the config file, emptying the instrumentationkey solved problem as well). See http://apmtips.com/blog/2015/02/02/developer-mode/
Reference: http://blogs.msdn.com/b/visualstudioalm/archive/2015/01/07/application-insights-support-for-multiple-environments-stamps-and-app-versions.aspx
You can try to use TelemetryConfiguration.DisableTelemetry Property
Something like this way..
#if DEBUG
TelemetryConfiguration.Active.DisableTelemetry = true;
#endif
As an addition to the other solutions I would suggest to add the following let's say to the Global.asax:
protected void Application_Start()
{
DisableApplicationInsightsOnDebug();
// do the other stuff
}
/// <summary>
/// Disables the application insights locally.
/// </summary>
[Conditional("DEBUG")]
private static void DisableApplicationInsightsOnDebug()
{
TelemetryConfiguration.Active.DisableTelemetry = true;
}
The advantage of this is, that it needs no change to the configs and it works better with some tools like ReSharper which will understand it better than #-directives.
NOTE: This option only existed in Visual Studio 2019
For ASP.NET Core projects the App Insights are ON by default, which actually logs a ton of info into debug window.
To disable it go to "TOOLS --> Options --> Projects and Solutions --> Web Projects" and check "Disable local Application Insights for Asp.Net Core web projects."
Below is the image for disabling local app insights.
For more info on the issue you can see the official github issue here
Running an ASP.NET Core 2.1 web application with Visual Studio 2017 (15.9.2) the "Disable local Application Insights for Asp.Net Core web projects" did not clear up the output in my Debug window.
However adding the following to Configure() in Startup.cs did the job;
if (_env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
TelemetryConfiguration.Active.DisableTelemetry = true;
TelemetryDebugWriter.IsTracingDisabled = true;
}
Note that the IsTracingDisabled was the key solution, but I left in DisableTelemetry for good measure! Plus having both lines next to one another is helpful when searching for similar references between .NET Framework & .NET Core projects in the same solution.
As explained in the question not deploying or deploying an ApplicationInsights.config without <instrumentationkey>key</instrumentationkey> block events from being generated.
You can then put the instrumentation key in code (only on release in my case)
#if !DEBUG
Microsoft.ApplicationInsights.Extensibility.TelemetryConfiguration.Active.InstrumentationKey = "instrumentation key";
#endif
Every TelemetryClient created after this call will have the correct key and will track events so you don't have to change the code in all places.
Not calling the method above or leaving the parameter empty will block events because there isn't a key configured.
Basically the ApplicationInsights.config file overrides any code that set the instrumentation key, removing the <instrumentationkey>key</instrumentationkey> inside it will let you use code to configure the key.
If you remove the file completely it doesn't work.
Here is the confirm:
"If you want to set the key dynamically - for example if you want to send results from your application to different resources - you can omit the key from the configuration file, and set it in code instead."
Reference: https://azure.microsoft.com/en-us/documentation/articles/app-insights-configuration-with-applicationinsights-config/#_instrumentationkey
As of ASP.NET Core 3.1:
To disable logging any App Insights telemetry to Azure:
public void Configure(IApplicationBuilder app, IHostingEnvironment env,
TelemetryConfiguration configuration)
{
configuration.DisableTelemetry = true;
}
To disable logging telemetry events to the Output window:
TelemetryDebugWriter.IsTracingDisabled = true;
(the above can be called from anywhere, but the sooner in your application's lifecycle, the better).
Both can be used together to suppress all Application Insights activity in your code. I guard with an #if DEBUG directive to ensure that AppInsights does nothing on my local machine, but does emit events when published to our dev server in the Azure cloud:
public void Configure(IApplicationBuilder app, IHostingEnvironment env,
TelemetryConfiguration configuration)
{
if (env.IsDevelopment())
{
#if DEBUG
configuration.DisableTelemetry = true;
TelemetryDebugWriter.IsTracingDisabled = true;
#endif
}
}
I have decided to use both approaches. I have moved the InstrumentationKey to the Web.config and it will be replaced by the transformation from Web.Release.config or Web.Debug.config. (don't forget to remove it from the ApplicationInsights.config file). Then I have called this method from the Application_Start()
public static void RegisterTelemetryInstrumentationKey()
{
if (string.IsNullOrWhiteSpace(WebConfigurationManager.AppSettings["TelemetryInstrumentationKey"])
{
TelemetryConfiguration.Active.DisableTelemetry = true;
}
else
{
TelemetryConfiguration.Active.InstrumentationKey = AppSettings.TelemetryInstrumentationKey;
}
}
I've just had the same issue.
We wanted to control the setting in the web.config so added a DisableAITelemetry key within our app settings:
<appSettings>
<add key="DisableAITelemetry" value="true" />
</appSettings>
With live and demo builds, we won't include a value (so that it defaults to false).
We could then solve it by adding this:
bool disable;
string disableAiTelemetry = ConfigurationManager.AppSettings["DisableAITelemetry"];
bool.TryParse(disableAiTelemetry, out disable);
TelemetryConfiguration.Active.DisableTelemetry = disable;
Slightly different play on some of the other solutions. Put this in your global.asax:
Microsoft.ApplicationInsights.Extensibility.Implementation.TelemetryDebugWriter.IsTracingDisabled = Debugger.IsAttached;
It will turn off app insights debug output when running under the debugger, but allow it under Ctrl+F5 scenarios and debug builds published to test servers
We've found the easiest way to prevent it from tracing into the Debug log is as simple as:
Extensibility.Implementation.TelemetryDebugWriter.IsTracingDisabled = True
In an ASP.NET Core application, you can add the following to the Startus.cs to turn off Application Insights in the Development environment:
if (env.IsDevelopment()) {
TelemetryConfiguration.Active.DisableTelemetry = true;
}
Add this to the constructor, right after the builder.AddApplicationInsightsSettings(); command and you'll no longer see AI logs clogging up your debug console.
Microsoft.ApplicationInsights.AspNetCore Version 2.1
services.AddApplicationInsightsTelemetry(options =>
{
options.EnableDebugLogger = false;
});
The solution suggested above has been deprecated (reference: https://github.com/microsoft/applicationinsights-dotnet/issues/1152). In dotnet core the new way to dynamically disable telemetry is this:
public void ConfigureServices(IServiceCollection services)
{
services.AddApplicationInsightsTelemetry();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, TelemetryConfiguration configuration)
{
configuration.DisableTelemetry = true;
...
}
(reference: https://learn.microsoft.com/en-us/azure/azure-monitor/app/asp-net-core#disable-telemetry-dynamically)
And if you want to disable telemetry in a custom WebApplicationFactory (when doing integration tests) you can do this:
public class CustomWebApplicationFactory<TStartup> : WebApplicationFactory<TStartup> where TStartup : class
protected override void ConfigureWebHost(IWebHostBuilder builder)
{
builder.ConfigureServices((context, services) =>
{
// Disable application insights during testing.
services.Configure<TelemetryConfiguration>(
(telemetryConfig) => {
telemetryConfig.DisableTelemetry = true;
});
});
base.ConfigureWebHost(builder);
}
}
For more context about integration testing see https://learn.microsoft.com/en-us/aspnet/core/test/integration-tests?view=aspnetcore-5.0
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
#region Disable Application Insights debug informations
#if DEBUG
TelemetryConfiguration.Active.DisableTelemetry = true;
TelemetryDebugWriter.IsTracingDisabled = true;
#endif
#endregion
//...
}
Since .NET Core 3.1:
var telemetryConfiguration = TelemetryConfiguration.CreateDefault();
telemetryConfiguration.DisableTelemetry = true;
var telemetryClient = new TelemetryClient(telemetryConfiguration); // Use this instance
TelemetryDebugWriter.IsTracingDisabled = true;
We can modify the file “appsetting.json” and add the following attributes
"ApplicationInsights": {
"EnableRequestTrackingTelemetryModule": false,
"EnableEventCounterCollectionModule": false,
"EnableDependencyTrackingTelemetryModule": false,
"EnablePerformanceCounterCollectionModule": false,
"EnableDiagnosticsTelemetryModule": false
}
More information you can find here.

Unable to use session in ASP.Net vNext Project

I have an ASP.Net vNext project that uses Session. But I am getting this error while trying to get/set values in the session.
An exception of type 'System.InvalidOperationException' occurred in Microsoft.AspNet.Http.Core.dll but was not handled in user code
Additional information: Session has not been configured for this application or request.
Here's my controller method:
[AllowAnonymous]
[HttpGet("/admin")]
public IActionResult Index()
{
if (Context.Session.GetString("UserName") == null) // error thrown here
{
return RedirectToAction("Login");
}
return View();
}
I have added the KVM package "Microsoft.AspNet.Session": "1.0.0-beta3" in my project.json file as well and have configured my application to use session via my Startup.cs like so:
public void ConfigureServices(IServiceCollection services)
{
// code removed for brevity
services.AddCachingServices();
services.AddSessionServices();
}
public void Configure(IApplicationBuilder app)
{
app.UseMvc();
app.UseInMemorySession(configure: s => s.IdleTimeout = TimeSpan.FromMinutes(30));
}
I have looked at the vNext documentation on Github but it does not provide much information about ASP.Net sessions. What am I doing wrong?
So I figured this out. The fix was quite simple actually. Since ASP.Net adds the middlewares sequentially into the request pipeline, all I needed to do was use the session middleware before using MVC. More info here: https://stackoverflow.com/a/29569746/832546
Fixed code:
public void Configure(IApplicationBuilder app)
{
app.UseInMemorySession(configure: s => s.IdleTimeout = TimeSpan.FromMinutes(30));
app.UseMvc();
}
Thanks to #acrhistof the link helped.
So if you are using RC1:
add this these dependencies in project.json:
"Microsoft.AspNet.Session": "1.0.0-rc1-final",
"Microsoft.Extensions.Caching.Memory": "1.0.0",
in Startup.cs file:
public void ConfigureServices(IServiceCollection services)
{
services.AddCaching();
services.AddSession();
services.AddMvc();
}
and
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
app.UseSession(); //outside of dev if (env.IsDevelopment())
....
}
It seems like things changed once again and the well-known ASP.NET session has to be configured differently in the rc1. (no UseInMemorySession() or other AppBuilder methods are related to Session, now it is added as a service).
In general Session has to be installed, configured, and then used. All these steps are quite new and somewhat unusual. Moreover, it depends on Cache:
Session is built on top of IDistributedCache, so you must configure
this as well, otherwise you will receive an error.
The quotation above is from ASP.NET 5 docs. All you need to do is described here: https://docs.asp.net/en/latest/fundamentals/app-state.html#installing-and-configuring-session.

Categories

Resources