Where and how to put azure application insights exceptions on global level in .net core project? I am having app insights installed and I can follow telemetry in azure, but exceptions are missing for failed requests.
One approach would be to create custom middleware which would catch the error and send the exception to AppInsights.
using System;
using System.Threading.Tasks;
using Microsoft.ApplicationInsights;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
namespace Middleware
{
public static class ApplicationBuilderExtensions
{
public static IApplicationBuilder UseHttpException(this IApplicationBuilder application)
{
return application.UseMiddleware<HttpExceptionMiddleware>();
}
}
public class HttpExceptionMiddleware
{
private readonly RequestDelegate _next;
public HttpExceptionMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext context)
{
try
{
await _next.Invoke(context);
}
catch (Exception ex)
{
var telemetryClient = new TelemetryClient();
telemetryClient.TrackException(ex);
//handle response codes and other operations here
}
}
}
}
Then, register the middleware in the Startup's Configure method:
app.UseHttpException();
Related
How to add custom dimension to Application Insights traces from .NET Core?
Any pointers are welcome.
If it's a .net core web project, you can use ITelemetryInitializer to add custom dimension.
First, add a new class named MyTelemetryInitializer to the project:
public class MyTelemetryInitializer: ITelemetryInitializer
{
public MyTelemetryInitializer()
{
}
public void Initialize(ITelemetry telemetry)
{
if (telemetry is TraceTelemetry traceTelemetry)
{
if (!traceTelemetry.Properties.ContainsKey("my_custom_1"))
{
//add the custom dimension here
traceTelemetry.Properties["my_custom_1"] = "test 12346";
}
}
}
}
Then in the Startup.cs -> ConfigureServices method, add these lines of code:
services.AddApplicationInsightsTelemetry();
services.AddSingleton<ITelemetryInitializer, MyTelemetryInitializer>();
And for testing purpose, in the HomeController, I have this Index method to send trace message:
public IActionResult Index()
{
TelemetryClient client = new TelemetryClient();
client.TrackTrace("it is a trace message from index page");
return View();
}
At last, run the project. Then nav to azure portal -> application insights, you can see the custom dimension is added.
better cast to ISupportProperties
if (telemetry is ISupportProperties traceTelemetry)
I'm having the weirdest issue and I have no idea why.
When deploying our .net core 2.2 api to our local IIS server I get the following error message:
HTTP Error 502.5 - ANCM Out-Of-Process Startup Failure
After checking the event log I this is the error that I find:
Application: dotnet.exe
CoreCLR Version: 4.6.27207.3
Description: The process was terminated due to an unhandled exception.
Exception Info: System.InvalidOperationException: No service for type 'Digitise.Infrastructure.Services.DatabaseMigrator' has been registered.
at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType)
at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService[T](IServiceProvider provider)
at Digitise.ApiBase.BaseProgram.Initialise(String[] args, IWebHost host) in C:\Projects\Digitise.AspNetCore\Digitise.ApiBase\BaseProgram.cs:line 17
at Digitise.Api.Program.Main(String[] args) in C:\Projects\Digitise.AspNetCore\Digitise.Api\Program.cs:line 27
It seems like the DI is not working correctly! The weird thing is if I run the api.exe or dotnet api.dll the API works perfectly :/
Anyone have any ideas? :)
Program.cs
public class Program
{
public static object _lock = new object();
public static bool _init = false;
public static void Main(string[] args)
{
var host = CreateWebHostBuilder(args);
Initialise(args, host);
}
public static IWebHost CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
//.UseIISIntegration()
.UseIIS()
.UseNLog()
.UseShutdownTimeout(TimeSpan.FromSeconds(10))
.Build();
public static void Initialise(string[] args, IWebHost host)
{
var logger = NLogBuilder.ConfigureNLog(Path.Combine(Directory.GetCurrentDirectory(), "NLog.config")).GetCurrentClassLogger();
try
{
logger.Debug("App init");
using (var scope = host.Services.CreateScope())
{
var services = scope.ServiceProvider;
try
{
if (!_init)
{
lock (_lock)
{
if (!_init)
{
lock (_lock)
{
services.GetRequiredService<DatabaseMigrator>().Migrate();
}
}
}
}
}
catch (Exception ex)
{
logger.Error(ex, "An error occurred while starting up the app.");
throw;
}
}
host.Run();
}
catch (Exception e)
{
logger.Error(e, "Stopped app due to exception");
throw;
}
}
}
DatabaseMigrator.cs
public class DatabaseMigrator
{
private readonly TenantDbContext _tenantDbContext;
private readonly IOptions<DatabaseConfiguration> _databaseConfig;
private readonly ILogger<DatabaseMigrator> _logger;
private readonly AdminTenantDbInitialiser _adminTenantDbInitialiser;
public DatabaseMigrator(TenantDbContext tenantDbContext, IOptions<DatabaseConfiguration> databaseConfig, ILogger<DatabaseMigrator> logger, AdminTenantDbInitialiser adminTenantDbInitialiser)
{
_tenantDbContext = tenantDbContext;
_databaseConfig = databaseConfig;
_logger = logger;
_adminTenantDbInitialiser = adminTenantDbInitialiser;
}
public void Migrate()
{
//migration logic
}
}
I've just gone through a lot of pain fixing a similar problem. Pretty sure the problem is you using Directory.GetCurrentDirectory(), this does odd things when running with in-process hosting as in IIS. I replaced it with Assembly.GetExecutingAssembly().Location and all worked fine.
Clue came from Dotnet Core Multiple Startup Classes with In-Process Hosting
In my case the issue started to show up after I updated some Nuget packages. Installing the latest .NET Core SDK has helped.
SignalR works on localhost but doesn't work when is deployed in Azure
Asp.net Core 1.0.0 (.Net Framework 4.6.1)
SignalR.Core 2.2.1
public static void UseSignalR2(this IApplicationBuilder app)
{
app.UseAppBuilder(appBuilder => {
appBuilder.MapSignalR(new HubConfiguration());
});
GlobalHost.HubPipeline.AddModule(new ErrorHandlingPipelineModule());
GlobalHost.HubPipeline.AddModule(new LoggingPipelineModule());
}
SignalR.js 2.2.1 with default settings
$.connection.hub.url = '/signalr';
Expected behavior
200 for url:
https://(name).azurewebsites.com/signalr/negotiate?clientProtocol=1.5&connectionData=%5B%7B%22name%22%3A%22productsimporthub%22%7D%5D&_=1472811629592
Actual behavior
/signalr/negotiate - on localhost returns 200 but for deployed app in azure returns 404
/signalr - works on both - Protocol error: Unknown transport.
/signalr/hubs - works on both - returns the SignalR js correctly
To find out the real cause of the issue you need to navigate to the negotiate url, and look for the response.
If the response tells you something about a 'CryptographicException: The data protection operation was unsuccessful...'. This is how to fix it.
1) Create a custom IDataProtectionProvider
2) Configure signalr
internal class MachineKeyProtectionProvider : IDataProtectionProvider
{
public IDataProtector Create(params string[] purposes)
{
return new MachineKeyDataProtector(purposes);
}
}
internal class MachineKeyDataProtector : IDataProtector
{
private readonly string[] _purposes;
public MachineKeyDataProtector(string[] purposes)
{
_purposes = purposes;
}
public byte[] Protect(byte[] userData)
{
//return MachineKey.Protect(userData, _purposes);
return userData;
}
public byte[] Unprotect(byte[] protectedData)
{
//return System.Web.Security.MachineKey.Unprotect(protectedData, _purposes);
return protectedData;
}
}
I use katana extension methods to bridge the IAppBuilder to IApplicationBuilder.
This allows your owin middleware to connect to asp.net core. It is important to use the RunSignalr method
app.UseAppBuilder(appBuilder =>
{
appBuilder.SetDataProtectionProvider(new MachineKeyProtectionProvider());
appBuilder.Map("/signalr", map =>
{
var hubConfiguration = new HubConfiguration
{
EnableDetailedErrors = true
};
map.RunSignalR(hubConfiguration);
});
});
I'm using Ninject for dependency injection in my ASP.NET Web Api 2 project. Everything is working perfectly locally through Visual Studio and IIS Express, but when I deploy to IIS, the dependency's are not resolved. Below is my Startup.cs
public partial class Startup
{
public void Configuration(IAppBuilder app)
{
var webApiConfiguration = new HttpConfiguration();
webApiConfiguration.EnableCors();
webApiConfiguration.SuppressDefaultHostAuthentication();
webApiConfiguration.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
webApiConfiguration.MapHttpAttributeRoutes();
app.UseNinjectMiddleware(CreateKernel).UseNinjectWebApi(webApiConfiguration);
ConfigureAuth(app);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
app.Run(async context =>
{
await context.Response.WriteAsync("Welcome to Web API");
});
}
private static IKernel CreateKernel()
{
var kernel = new StandardKernel();
kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);
kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();
kernel.Load(new CourseModule(), new DataPullModule(), new DegreeModule(), new ResponseModule(), new RestSharpModule());
return kernel;
}
}
The error I get is when trying to access one of my controllers is below:
An error occurred when trying to create a controller of type 'DegreeController'. Make sure that the controller has a parameterless public constructor.
Here is my constructor for the DegreeController:
public DegreeController(IDegreeMapper degreeMapper, IDegreeRepository degreeRepository)
{
_degreeMapper = degreeMapper;
_degreeRepository = degreeRepository;
}
And here is the DegreeModule where I bind interfaces to classes.
public class DegreeModule : NinjectModule
{
public override void Load()
{
Bind<IDegreeController>().To<DegreeController>().InRequestScope();
Bind<IDegreeMapper>().To<DegreeMapper>().InRequestScope();
Bind<IDegreeRepository>().To<DegreeRepository>().InRequestScope();
Bind<IDegreeRatingCalculator>().To<DegreeRatingCalculator>().InRequestScope();
}
}
var kernel = CreateKernel();
app.UseNinjectMiddleware(() => kernel).UseNinjectWebApi(configuration);
I have an OWIN pipeline using Nancy:
public class Startup
{
public void Configuration(IAppBuilder app)
{
app.UseNancy();
}
}
The UseNancy() is actually a call to my own custom extension method defined in this gist: https://gist.github.com/TheFastCat/0b7635d9e5795b44e72e
This code is executed both as an Azure Website or an Azure Cloud Service. Based on the context it is executing within I want to use a particular favicon, loaded as an embedded resource from a separate assembly. I do this by specifying separate NancyBootstrappers (each loading the proper favicon for its context).
Is there a more elegant solution to determining the runtime application that is executing the OWIN pipeline? Currently I check app.Properties["host.AppName"] ; however while the Website's app name matches it's assembly configuration, the CloudService app is the name of the Owin startup assembly.class. (see gist). It's cloogey.
Is there a more elegant/simple solution for specifying a custom favicon within Nancy for each of my web applications than creating separate bootstrappers and doing runtime application context checks?
I solved this problem with the help of others on the https://jabbr.net/#/rooms/owin and https://jabbr.net/#/rooms/nancyfx chat boards
Yes. You can contextually check the OWIN host properties:
if (app.Properties.ContainsKey("System.Net.HttpListener"))
{
// self hosted application context
}
2.) Yes.
namespace ClassLib
{
public class Startup()
{
public Startup(byte[] favIcon) { ... }
public void Configuration(IAppBuilder app) { ... }
}
}
[assembly: OwinStartup(typeof(WebHost.Startup))]
namespace WebHost
{
public class Startup()
{
public voic Configuration(IAppBuilder app)
{
new ClassLib.Startup(webhostFavIcon).Configuration(app);
}
}
}
namespace SelfHost
{
private class Program()
{
public void Main(string[] args)
{
using(WebApp.Start(app => new ClassLib.Startup(selfHostFavIcon).Configuration(app))
{}
}
}
}