Azure Application Insights not showing data - asp.net

I have an ASP.NET Core application running as Azure App Service. Azure Application Insights is enabled (I followed these instructions). The problem is my instance of Azure Insights on Azure Portal isn't showing any useful data except for Live Metrics (see the screenshot). As you can see there are multiple requests and custom events on the screenshot.
However, when I open Transaction search it shows nothing (see the screenshot).
Events page is empty as well (see the screenshot).
So far I double-checked an InstrumentKey. Also I tried to use ConnectionString instead of InstrumentKey, but it didn't help.
My app is running on .NET Core 3.1. I installed the latest version of Microsoft.ApplicationInsights.AspNetCore package which is 2.19.0.
Here is how logging is configured in Program.cs:
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.ConfigureLogging(builder =>
{
builder.AddFilter<ApplicationInsightsLoggerProvider>("", LogLevel.Information);
});
And below is code from Startup.cs:
services.AddApplicationInsightsTelemetry(new ApplicationInsightsServiceOptions
{
ConnectionString = Environment.GetEnvironmentVariable("APPLICATIONINSIGHTS_CONNECTION_STRING")
});
LogLevel is also configured in appsettings.json:
"Logging": {
"LogLevel": {
"Default": "Warning"
},
"ApplicationInsights": {
"LogLevel": {
"Default": "Information"
}
}
Update:
My Admin who has more permissions can see all data, including events, performance operations etc. So I suppose there's something to do with permissions. Though it's strange that I'm not seeing any warning messages. The Admin assigned me more roles (see the screenshot), but it didn't make any difference.
I would appreciate any help on this issue!

After tearing almost all hair off my head I finally solved the issue!
Turned out the instance of Azure Application Insights was linked to a Log Analytic Workspace that belonged to a Resource Group to which I didn't have access. So logs were stored properly, but I didn't have permission to read them.
My admin solved the issue by creating a new instance of Azure Application Insights which was linked to a Log Analytic Workspace within my Resource Group.
To anyone who isn't familiar with Log Analytic Workspace - it can be specified when you create a new instance of Azure Application Insights (see the screen).
Thanks everyone for trying to help me!
UPDATE: As Jonathan L. mentioned in the comments, instead of creating a new Application Insights instance, one can just change Workspace in Properties.

I have tried the same and can able to see the logs inside portal .
As Peter Bons suggested make sure that you are using ILogger in your controller .
Here are the steps i have followed .
I have download an sample project from GitHub and after extract open project in Visual studio and configure with Application insight telemetry . Updated latest Microsoft.ApplicationInsights.AspNetCore to 2.19.0
And added instrumentation key in my appsettings.json which copied from Azure portal>Application insight(my applnsight)>overview.
{
"Logging": {
"ApplicationInsights": {
"LogLevel": {
"Default": "Debug",
"Microsoft": "Error"
}
},
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*",
"ApplicationInsights": {
"InstrumentationKey": "mykey",
"ConnectionString": "InstrumentationKey=6xxxxxx-xxxxx-xxxx-xxxx-0000000xxxxxxxx.in.applicationinsights.azure.com/"
}
}
Ilogger configuration in my controller.cs
namespace ApplicationInsightsTutorial.Controllers
{
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
private static readonly string[] Summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
private readonly ILogger<WeatherForecastController> _logger;
public WeatherForecastController(ILogger<WeatherForecastController> logger)
{
_logger = logger;
}
[HttpGet]
public IEnumerable<WeatherForecast> Get()
{
var iteracion = 4;
_logger.LogDebug($"Debug {iteracion}");
_logger.LogInformation($"Information {iteracion}");
_logger.LogWarning($"Warning {iteracion}");
_logger.LogError($"Error {iteracion}");
_logger.LogCritical($"Critical {iteracion}");
try
{
throw new NotImplementedException();
}
catch (Exception ex)
{
_logger.LogError(ex, ex.Message);
}
var rng = new Random();
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateTime.Now.AddDays(index),
TemperatureC = rng.Next(-20, 55),
Summary = Summaries[rng.Next(Summaries.Length)]
})
.ToArray();
}
}
}
In startup.cs added
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddApplicationInsightsTelemetry();//telemetry added
}
After all that above configuration run the application and navigate to Azure portal to check the logs .
Make sure that you have provided the log information which you want to check as example in my controller.cs .
from the logs we can see the exceptions/errors with line of code as well .
Here are some screenshot for reference:
For more information please refer this SO Thread .

Related

Adding logs on the Azure Application insights from the ASP.Net MVC framework 4.6.2

I wanted to add logs on the Azure Application Insights in my application, ASP.Net Web application MVC, .Net Framework is 4.6.2.
I do have added references to below nuget packages
Microsoft.ApplicationInsights
Microsoft.Extensions.Logging
I do have added below code in Global.asax.cs in the applicatin_start
TelemetryConfiguration.Active.TelemetryInitializers.Add(new MyTelemetryInitializer());
Inside HomeController.cs, I have added below code, but it is giving me below error at the line _logger.LogTrace()
Error
System.ArgumentNullException: 'Value cannot be null.
Parameter name: logger'
Code
public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;
public HomeController()
{
IServiceCollection services = new ServiceCollection();
IServiceProvider serviceProvider = services.BuildServiceProvider();
_logger = serviceProvider.GetService<ILogger<HomeController>>();
}
public ActionResult Index()
{
ViewBag.Title = "Home Page";
_logger.LogTrace("Some trace message from Version 462");
return View();
}
}
Please let me know where I am going wrong.
Thanks,
Tushar
Initially, you need to add Application Insights. Below are the steps you can follow to add Application Insights to your Application.
Navigate to your Project >> Add Application Insights Telemetry >> Application Insights Sdk (local) >> Next >> Finish >> Close.
You can register the initializer through applicationinsights.config file, while Adding Application Insights automatically we need to add the instrumentation key to ApplicationInsights.config before closing the </ApplicationInsights> tag file.
<InstrumentationKey>"your-instrumentation-key-goes-here"</InstrumentationKey>
OR
protected void Application_Start()
{
// ...
TelemetryConfiguration.Active.TelemetryInitializers.Add(new MyTelemetryInitializer());
}
And while logging in from your Home Controller try
public class HomeController : Controller
{
ILogger<HomeController> _logger;
public HomeController(ILogger<HomeController> logger)
{
_logger = logger;
}
public ActionResult Index()
{
_logger.LogInformation("Log message in the Index() method");
return View();
}
}
After updating the Nuget packages, you can run your application where you can observe that telemetry will be submitted to Application Insights when you navigate the site's pages.
If Adding Application Insights Automatically isn't working, then you can try manually from HERE.
REFERENCE :
Configure monitoring for ASP.NET with Azure Application Insights
azure - Application Insights for WebAPI application - Stack Overflow
Logger.LogTrace() does not write message to application insights
Below are the steps to resolve this issue.
Navigate to your Project >> Add Application Insights Telemetry >> Application Insights Sdk (local) >> Next >> Finish >> Close.
In the Global.asax.cs add below line
TelemetryConfiguration.Active.TelemetryInitializers.Add(new MyTelemetryInitializer());
Wherever wanted to add application insights add below code, you can create common logger file also.
TelemetryClient client = new TelemetryClient(TelemetryConfiguration.Active);
client.TrackTrace("Custom Track Trace");
client.TrackAvailability(new AvailabilityTelemetry() { Name = "Availablilty Test"});
client.TrackDependency(new DependencyTelemetry() { Name = "Dependency Test" });
client.TrackEvent(new EventTelemetry() { Name = "Event Test" });
client.TrackException(new ExceptionTelemetry() { Message = "Exception Test" });
client.TrackMetric(new MetricTelemetry() { Name = "Metric Test" });
client.TrackPageView(new PageViewTelemetry() { Name = "PageView Test" });
client.TrackRequest(new RequestTelemetry() { Name = "Request Test" });

Serilog missing exception in generic logger

In a controller method, the generic logger doesn't seem to have the defined enrichers.
Here is the controller:
public class TestController : Controller
{
ILogger _logger;
public TestController(ILogger<TestController> logger)
{
_logger = logger;
}
public IActionResult action()
{
try
{
throw new NullReferenceException();
}
catch(Exception e)
{
Serilog.Log.Error(ex, "action KO");
_logger.LogError("action KO", ex);
}
}
}
The appsettings.json:
{
"Serilog": {
"MinimumLevel": {
"Default": "Debug",
},
"WriteTo": [
{
"Name": "Console"
},
{
"Name": "File",
"Args": {
"path": "Log/api.log",
"outputTemplate": "{Timestamp} [{Level:u3}] ({SourceContext}) {Message}{NewLine}{Exception}",
"rollingInterval": "Day",
"retainedFileCountLimit": 7
}
}
],
"Enrich": [
"FromLogContext",
"WithExceptionDetails"
]
}
}
Host building:
IHost host = Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
webBuilder.UseUrls($"http://*:12345");
})
.UseSerilog((hostingContext, loggerConfiguration) => loggerConfiguration
.ReadFrom.Configuration(hostingContext.Configuration)
)
.Build()
;
Output in file / console:
02/18/2021 12:24:57 +01:00 [ERR] () action KO
System.NullReferenceException: Object reference not set to an instance of an object.
at App.TestController`1.action()
02/18/2021 12:24:57 +01:00 [ERR] (App.TestController) action KO
So when I try to use a generic logger, the exception is omitted. Wheras the static logger writes it.
Am I missing something like a provider for controllers logger or is it meant to be done by UseSerilog?
EDIT
Tried UseSerilog with writeToProviders: true => no effect
Tried AddSerilog as a logging builder => no effect
services.AddLogging(loggingBuilder => loggingBuilder.AddSerilog(
new LoggerConfiguration().ReadFrom.Configuration(Configuration).CreateLogger(), true));
Tried AddSerilogServices => no effect
public static IServiceCollection AddSerilogServices(
this IServiceCollection services,
LoggerConfiguration configuration)
{
Log.Logger = configuration.CreateLogger();
AppDomain.CurrentDomain.ProcessExit += (s, e) => Log.CloseAndFlush();
return services.AddSingleton(Log.Logger);
}
First, please change
_logger.LogError("action KO", ex);
to
_logger.LogError(ex, "action KO");
Testing the following try/catch
try
{
throw new NullReferenceException();
}
catch (Exception ex)
{
_logger.LogError(ex, "action KO");
}
... writes this to log file:
02/27/2021 22:55:59 +01:00 [ERR] (MyMicroservice.Controllers.WeatherForecastController) action KO
System.NullReferenceException: Object reference not set to an instance of an object.
at MyMicroservice.Controllers.WeatherForecastController.Get() in C:\Prosjekter\MyMicroservice\WebApp\Controllers\WeatherForecastController.cs:line 51
After checking your configuration with doc, and some testing, the part you've added to your question, seems OK to me.
I've added some words about an interesting finding during testing and reading the docs, and finally there is a Program.cs you may want to have a look at.
TL;DR: Serilog recommends two-stage initialization in order to have a
temporary logger before starting the host. The code below shows
how to skip stage #1 with a tiny change and still get a logger before starting the host.
Serilog.AspNetCore doc:
https://github.com/serilog/serilog-aspnetcore#inline-initialization
At the very beginning of Program#Main, you will have a Serilog.Core.Pipeline.SilentLogger.
If you follow the recommendations, you will have a Serilog.Extensions.Hosting.ReloadableLogger after stage #1.
Stage #1 looks like this and requires Nuget Serilog.Extensions.Hosting
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Override("Microsoft", LogEventLevel.Information)
.Enrich.FromLogContext()
.WriteTo.Console()
.CreateBootstrapLogger();
In order to try to save us for some code lines and an additional dependency, comment out stage #1, and let's try the following approach to see if we can get an initialized logger before starting the web host.
var webHost = CreateHostBuilder(args).Build();
After this line, we do have an instance of Serilog.Core.Logger, which is the same as we'll end up with when using CreateHostBuilder(args).Build().Run(). Hence, I ended up with the below Program.cs where I omitted stage #1 entirely, but kept stage #2.
This should not have any side-effects, doc says:
To address this, Serilog supports two-stage initialization. An initial
"bootstrap" logger is configured immediately when the program starts,
and this is replaced by the fully-configured logger once the host has
loaded.
Please note that after commenting out lines in code from doc, UseSerilog part is now equal to config from question.
I'm using appsettings.json from your question.
I have no Serilog config in Startup.cs.
using System;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Serilog;
using Microsoft.Extensions.DependencyInjection;
namespace MyMicroservice
{
public class Program
{
public static void Main(string[] args)
{
// Serilog.Core.Pipeline.SilentLogger at this stage
var webHost = CreateHostBuilder(args).Build();
// Serilog.Core.Logger at this stage
// proof-of-concept: This will log to file before starting the host
var logger = webHost.Services.GetService<ILogger<Program>>();
logger.LogWarning("Hello from Program.cs");
try
{
Log.Information("Starting up");
webHost.Run();
}
catch (Exception ex)
{
Log.Fatal(ex, "Application start-up failed");
}
finally
{
Log.CloseAndFlush();
}
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.UseSerilog((context, services, configuration) => configuration
.ReadFrom.Configuration(context.Configuration)
/*.ReadFrom.Services(services) not required for this case */
/*.Enrich.FromLogContext() already configured in appsettings.json */
/*.WriteTo.Console() already configured in appsettings.json */
)
.ConfigureWebHostDefaults(webBuilder => webBuilder.UseStartup<Startup>());
}
}

SQLite data context in AspNetCore app not working

I have been trying to implement data access in my single page web app using the most recent scaffolding in Visual Studio 2019 and Entity Framework Core . I am using SDK version 3.1.100. Everything builds and runs but I am getting a runtime exception claiming "no such table: User". This makes me think that the connection between EF core and the database is good. Could be anything else as I am not having much luck with debugging. My SQLite database file and sqlite3.dll are contained in the project and have properties set to copy to output. The relevant code portions follow:
appsettings.json:
{
"ConnectionStrings": {
"Sqlite": "Data Source=HopeApp.db"
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*"
}
The following added to ConfigureServices in Startup.cs:
services.AddEntityFrameworkSqlite()
.AddDbContext<DatabaseContext>(options =>
options.UseSqlite(Configuration.GetConnectionString("Sqlite")));
The database context:
public class DatabaseContext: DbContext
{
public DbSet<datUser> User { get; set; }
public DbSet<datIESum> IESum { get; set; }
//
// https://learn.microsoft.com/en-us/ef/core/miscellaneous/configuring-dbcontext
//
public DatabaseContext(DbContextOptions<DatabaseContext> options)
: base(options) { }
}
And finally, the controller that attempts to retrieve the data:
[ApiController]
[Route("[controller]")]
public class UserController : ControllerBase
{
private readonly DatabaseContext db;
public UserController(DatabaseContext db)
{
this.db = db;
}
[HttpGet]
public IEnumerable<datUser> Get()
{
List<datUser> users = new List<datUser>();
using (this.db)
{
foreach (var user in this.db.User)
{
users.Append(user);
}
}
return users;
}
}
I examine the SQLite .db file in DB Brower and see the tables are present and verify that data is present. I have checked file permissions so everyone has full control. I don't know what else to check to track this down. Note that most of the examples these days are provided as "code first" instead of "database first" which works better for my application.
Here is a screen shot of HopeApp.db:
The error:
An exception of type 'Microsoft.Data.Sqlite.SqliteException' occurred in
Microsoft.EntityFrameworkCore.Relational.dll but was not handled in user code
SQLite Error 1: 'no such table: User'.
Any ideas or debugging suggestions? Any more information I can provide?
The error mentions that table User can not be found but the database file has table datUser.
The name of the property in the database context determines the expected table name. Either rename it to match, change the database file to match or use the fluent API to map between the two.
More information can be found here: https://learn.microsoft.com/en-us/ef/core/modeling/relational/tables

asp.net core 2.0 - Value cannot be null. Parameter name: connectionString

I had the following error in package manager console when Add-Migration
Value cannot be null. Parameter name: connectionString
This is my startup:
namespace MyProject
{
public class Startup
{
public IConfiguration Configuration { get; set; }
public Startup(IConfiguration config)
{
Configuration = config;
}
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContextPool<AppDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddTransient<IDevRepo, DevRepo>();
services.AddMvc();
services.AddMemoryCache();
services.AddSession();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseStatusCodePages();
app.UseStaticFiles();
app.UseMvcWithDefaultRoute();
app.Run(async (context) =>
{
await context.Response.WriteAsync(Configuration["Message"]);
});
}
}
}
program class:
public class Program
{
public static void Main(string[] args)
{
BuildWebHost(args).Run();
}
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((context, builder) => builder.SetBasePath(context.HostingEnvironment.ContentRootPath)
.AddJsonFile("appsettings.json")
.Build())
.UseStartup<Startup>()
.Build();
}
appsettings.json:
{
"Message": "Hello World",
"ConnectionStrings": {
"DefaultConnection": "Server=(localdb)\\MSSQLLocalDB;Database=NotMyFault;Trusted_Connection=True;MultipleActiveResultSets=true"
}
}
Interestingly if I run the app, it displays "Hello World", but when add migration it cannot find connectionString. Can someone please shed some lights here? Thanks.
This problem occurred when the connection string can't be found.
Probably you have the following code in Startup class:
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<BenchmarkContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("yourConnectionString name from appsettings.json")));
}
These methods solve your problem:
1- Instead of Configuration.GetConnectionString("yourConnectionString name from appsettings.json(in develop mode: 'appsettings.Development.json')") just put your connectionstring.
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<BenchmarkContext>(options =>
options.UseSqlServer("Data Source=.;Initial Catalog=Benchmark;Persist Security Info=True;User ID=****;Password=****"));
}
2- If you are going to use the Configuration file add these codes to Startup class:
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration;
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<BenchmarkContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("TestConnection")));
}
Appsettings.json file(in develop mode: 'appsettings.Development.json'):
{
"ConnectionStrings": {
"TestConnection": "Data Source=.;Initial Catalog=Benchmark;Persist Security Info=True;User ID=****;Password=****"
}
}
After that execute 'add-migration name' command in Package Manager Console
I had the same issue, but my solution was a lot simpler. All I did was to change the order of the appsettings.json from:
{
"Message": "Hello World",
"ConnectionStrings": {
"DefaultConnection": "Server=(localdb)\\MSSQLLocalDB;Database=NotMyFault;Trusted_Connection=True;MultipleActiveResultSets=true"
}
}
to:
{
"ConnectionStrings": {
"DefaultConnection": "Server=(localdb)\\MSSQLLocalDB;Database=NotMyFault;Trusted_Connection=True;MultipleActiveResultSets=true"
},
"Message": "Hello World"
}
I have a suspicion that there is a sequence/order of parameters in the appsettings.json file.
I had such issue when load tesing the service (I recommend it to all) and had ~3/1000 requests with errors,
so I changed
services.AddDbContextPool<AppDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
to
string connectionString = Configuration.GetConnectionString("DefaultConnection");
services.AddDbContextPool<AppDbContext>(options =>
options.UseSqlServer(connectionString));
So it reads connections string 1 time and doesn't use Configuration on every request. And now 100% requests are successful.
But it seems to be a bug in .Net Core
I found my own problem.
I have an AppDbContextFactory class which inherits IDesignTimeDbContextFactory. Deleting this class resolves this issue.
I had the same problem, because I was using the default value in Startup.cs.
I just edited Configuration property from:
public IConfiguration Configuration { get; }
to:
public IConfiguration Configuration;
and it worked!
If someone say why would be appreciated.
I had had a similar issue because of the following reasons:
appsettings.json was not included in the project
I was running the project from the path which did not contain appsettings.json
I had the same error and resolved it by moving "ConnectionStrings" to be the first variable in the appsettings.json file.
Probably, the issue is with your DotNetCliToolReference from the csproj file. If you migrate the project from an older version of asp.net core, the DotNetCliToolReference is not automatically updated.
Update the yourproject.csproj file to use the 2.0.0 version of the CLI as shown in the snippet bellow:
<ItemGroup>
...
<DotNetCliToolReference
Include="Microsoft.EntityFrameworkCore.Tools.DotNet"
Version="2.0.0" />
</ItemGroup>
Rerun, from the project folder, the dotnet command with -v switch to see results
dotnet ef database update -v
Also, recheck your Microsoft.EntityFrameworkCore nuget packages to reference the 2.0.0 version. Remove or update older EF packages. The minimum are:
Microsoft.EntityFrameworkCore.SqlServer
Microsoft.EntityFrameworkCore.Design
both 2.0.0 at this moment.
I had the same problem and what it is the I had to make sure that the name of the connection matches:
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
services.AddDbContext<MyContext>(options => options.UseSqlServer(Configuration["ConnectionStrings:DefaultConnection"]));
which ****ConnectionStrings:DefaultConnection*** it was where I had the whole problem.
Make sure that is the same in Startup.cs and appsettings.json(appsettings.Development.json in Vs 2019)
After I fixed this, everything was fine.
I had a similar issue. I had a typo in my appsettings.json. Changing ConnectionsStrings to ConnectionStrings did it for me!
I have solved my issue by setting right base path. The problem is the migrations or anything else from different packages uses wrong path to the appsetting.json file. Not sure if it's an official issue.
I have just changed my Startup.cs as follows:
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true)
.AddEnvironmentVariables();
Configuration = builder.Build();
}
After that you just need to copy your appsettings.json to the right place if it's missing there.
This worked flawlessly for me:
public IConfiguration Configuration;
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext.ApplicationDbContext>(options =>
//options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
options.UseSqlServer("Server=serverAddress; Database=dbName; user=username; password=pswd"));
}
The commented part is just as reference where to replace.
Another scenario can be where you set the configuration. set the connection string in appsettings.json instead of appsettings.Development.json
I had a similar problem when I specified the ".UseContentRoot" as the current process path.
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseUrls("http://*:3001")
.UseStartup<Startup>()
.UseContentRoot(Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName));
thus when running Add-Migration the process path is different from the project bin path therefore the process can't find the appsettings.json file.
when I removed the ".UseContentRoot" line the migration was successful
I'm stupid and I had typo
{
"Conn'ce'tionStrings": {
"DefaultConnection": "Data source=datingapp.db"
},
changed it to
{
"ConnectionStrings": {
"DefaultConnection": "Data source=datingapp.db"
},
I had a similar problem after trying to use new created project for ASP.NET Core 2.0 Web Api. As far as I found, the cause of the problem was that application settings specified for development environment were not added. I fixed it by updating startup file to the following:
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
this.Configuration = builder.Build();
}
In my case program class looks like the following:
public class Program
{
public static void Main(string[] args)
{
BuildWebHost(args).Run();
}
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.Build();
}
My problem was when I was trying to run App.dll within netcoreapp2.1 folder, but the right folder is netcoreapp2.1\publish\
If you have previously renamed your connection string in appsettings file and you have omitted to rename it in DesignTimeDbContextFactory class (if you have it in your project) and that is checked by Entity framework, then you may run in this issue.
If you are using an IDesignTimeDbContextFactory, you will need to add a default constructor to it with no parameters. Try something like this:
public DbContextFactory()
{
IConfigurationRoot configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddEnvironmentVariables()
.AddJsonFile("appsettings.json", false, true)
.Build();
_connectionString = configuration.GetConnectionString("ConnectionStringName");
}
For me it was that I had appSettings.json instead of appsettings.json for some reason (not quite sure if VS did that with a newly created project or I had renamed it to that). Once I changed the name, it worked fine.
I figured I would add what it was for me. I had followed a popular tutorial to add appsettings.json and dependency injection to a console application. I did not realize in the setup that it referenced the current directory and was using that to set the base path of the configuration builder. It worked fine when I was running locally, but as soon as I tried to deploy and have a SQL scheduled job run the command it was taking the directory where the command was being entered, not where the DLL was so it wasn't finding my appsettings.json file. I simply removed the lines that dealt with getting the current directory and setting that as the base path and it works fine. It seems like it defaults to the same folder as the DLL.
I had this problem due to a difference in connectionstring of appsetting.json file, and the GetConnectionString(connectionstrings) parameter in startup.cs. Once I removed extra s in startup.cs, the problem disappeared.
Check if ASPNETCORE_ENVIRONMENT variable is set up on the server correctly. Depending on that environment it may be taking appsettings.json instead of appsettings.Staging.json or appsettings.Production.json.
In my case i was using configuration["DbContext"]
services.AddDbContext<AstroBhaskarDbContext>(option =>
{
option.UseSqlServer(configuration["DbContext"]);
});
then i replaced configuration["DbContext"] to configuration.GetConnectionString("DbContext") as below
services.AddDbContext<AstroBhaskarDbContext>(option =>
{
option.UseSqlServer(configuration.GetConnectionString("DbContext"));
});

Running Kestrel yields empty browser

I've recently just upgraded Visual Studio 2015 with ASP.NET 5 beta8, which causes the strange shift from the old listener over to this new 'Kestrel' .. thing.
I've attempted to follow the instructions and get it to run, but I simply yield a console window that says...
Hosting environment: Development
Now listening on: http://localhost:5000
Application started. Press Ctrl+C to shut down.
Okay, so I navigate to http://localhost:5000, and ... nothing is there. My application doesn't run or anything.
I have tried to launch the default ASP.NET MVC sample project using Kestrel too, with the built in settings, and get the same result. I'm really unsure of what to do.
Here is what I've done so far...
I have it in my project.json file;
"dependencies": {
"Microsoft.AspNet.Server.Kestrel": "1.0.0-beta8",
},
"commands": {
"web": "Microsoft.AspNet.Server.Kestrel"
},
My program was working fine on beta7, using the old listener; But now even that doesn't work suddenly since installing beta8. I'm at the hair-pulling stage of frustration over this forced change. I can't get it to run in IIS either.
Per request, this is my Startup.cs file;
public Startup(IHostingEnvironment env, IApplicationEnvironment appEnv) {
// Setup configuration sources.
Configuration = new ConfigurationBuilder()
.SetBasePath(appEnv.ApplicationBasePath)
.AddJsonFile("config.json")
.AddEnvironmentVariables()
.Build();
}
public IConfiguration Configuration { get; set; }
// For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services) {
// Add MVC services to the services container.
services.AddMvc();
services.UseCookieAuthentication(o => {
//o.ExpireTimeSpan
o.CookieName = "3b7eaa9c-decd-4c5d-83f9-01f1f11a6e22";
});
}
public void Configure(IApplicationBuilder app) {
app.UseIdentity();
app.UseStaticFiles();
app.UseMvc(routes => {
// add the new route here.
routes.MapRoute(name: "areaRoute",
template: "{area:exists}/{controller}/{action}");
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}"
);
});
}
That understand in which place the request pipeline problem arise, enable logging in your application.

Resources